views:

57

answers:

0

HI, I have to unit test a Java class which implements DocumentListener interface. We are using Eclipse and Junit with EasyMock Framework. I'm a newbie to Unit testing and hence would appreciate a sample code using EasyMock.

The java class is:

public class ClassToBeTested implements DocumentListener 
{      
 private static final Color COLOR = Color.BLUE;
 /** Painter. */
private Highlighter.HighlightPainter painter = new    DefaultHighlighter.DefaultHighlightPainter  (COLOR);    
private int maxMessageSize;    
private JTextComponent component;

/*** The Constructor.
 * @param maxSize - The Maximum message size
 */
public ClassToBeTested(final int maxSize) 
{
   super();
   this.maxMessageSize = maxSize;
}
/**
 * Decorate the component.
 * @param c - The component to decorate
 */
 public final void decorate(final JTextComponent c) 
 {
     //TODO throw exception if already decorating
     this.component = c;
     component.getDocument().addDocumentListener(this);
}    
/**
* Remove Update.
* @param e - The event
*/
@Override
public final void removeUpdate(final DocumentEvent e) 
{
  handle(e);
}
/**
  * Insert Update.
   * @param e - The event
   */
    @Override
    public final void insertUpdate(final DocumentEvent e)
    {
  handle(e);
   }
   /**
    * Changed Update.* @param e - The event
     */
    @Override
     public final void changedUpdate(final DocumentEvent e) 
     {
  handle(e);
     }      
  /**
   * Handle the event.
   * @param e - The event
   */
   public void handle(final DocumentEvent e) 
    {
       Document doc = e.getDocument();
       try {
                String text = e.getDocument().getText(0, doc.getLength());      
          if (text.length() >= maxMessageSize) 
                 {
                  try
                     {
                         component.getHighlighter().addHighlight(                                              maxMessageSize, text.length() + 1, painter);
           } catch (BadLocationException ex) 
                      {
              System.out.println(ex.getMessage());
           }
          } else 
                 {
              component.getHighlighter().removeAllHighlights();
          }
        } catch (BadLocationException e1) 
        {
  System.out.println(e1.getMessage());
        }
    }
}