Simple unit testing
From Software By Jeff
So you recognize the value of testing your code, but you don't want to go through the rigors of learning [JUnit (http://junit.org)] or another testing engine. You're comfortable with making whatever your environment needs in the way of object set-up and calling the right methods. You still want a fairly automated way to run the tests, perhaps even adding tests without having to remember to put the test method in some stream of calls.
Try something like this:
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
Method[] methods = myTest.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (Modifier.isPublic(method.getModifiers()) && method.getName().startsWith("test")) {
try {
method.invoke(myTest, null);
} catch (Exception e) {
System.err.println("Method " + method.getName() + " failed:");
e.getCause().printStackTrace();
}
}
}
}
public void testThatFails() throws Exception {
throw new Exception("FAIL");
}
}
It's a very primative class, I'll grant you that. But it's got a little ease and elegance, thanks to our good friend Java Reflection.
This simple MyTest class contains one test method, aptly named testThatFails. The class has a main method that lets us run it as an application. It requires no additional classes or libraries as it stands.
Simply adding a public, parameterless method, whose name begins with "test" will be sufficient to ensure that the test is run the next time this class is executed.
You can make those methods do anything that you're comfortable with. The only key is to throw an execption, write a log, or pop-up a dialog box when you error...whatever makes you comfortable. The simple loop will capture and dump all Exceptions and dump them to the error console.
Of course, remove the testThatFails method, or you'll always have a failure.
Easy.