嗨,我必须对实现 DocumentListener 接口的 Java 类进行单元测试。我们将 Eclipse 和 Junit 与 EasyMock 框架一起使用。我是单元测试的新手,因此很欣赏使用 EasyMock 的示例代码。
java类是:
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());
}
}
}