I like to use static utilities to write parsing routines and other utility methods where code relies only on passed parameters and returns some type of immutable object such as String. However there’s one caveat – I also like to write JUnit tests for all these routines and here I’m seemingly out of luck. So I developed the following (singleton-based) pattern in implementing my static utilities. Let say I have MyUtils class and inside I want to have all API methods declared as “public static”.
- Define
private static final MyUtilsfiled - Place your utility method code inside a “regular” protected method
- Make your public static utility method refer to the internal MyUtils static instance
In code it will look like this
public class MyUtils {
private static final MyUtils UTILS = new MyUtils();
/**
* Hide constructor from the outside of the package
*/
MyUtils() {}
public static String parseUpdates(String html) throws IOException, SAXException {
return UTILS._parseUpdates(html);
}
String _parseUpdates(String html) throws IOException, SAXException {
InputSource s = new InputSource(new StringReader(html));
SaxParser parser = new SaxParser();
MyUpdatesHandler handler = new MyUpdatesHandler();
parser.setContentHandler(handler);
parser.parse(s);
return handler.getOutput();
}
}
With this code now you can now write JUnit test as follows (test class shell and javadoc comments are omitted for briefness)
MyUtils utils;
String html;
@Before
public void setUp() throws Exception {
utils = new MyUtils();
html = "<div>Hello World</div>";
}
@Test
public void testParseUpdates() throws Exception {
String out = utils._parseUpdates(html);
assertNotNull(out);
// any other assertions that make sense
}
Why don´t you call MyUtils.parseUpdates directly in your Test.
Thanks for pointing this out. The intent was to write a code that can be mocked not so much executed "as is" I'll add a comment