Software By JeffMain Page | About | Help | FAQ | Special pages | Log in
The Free Encyclopedia
Printable version | Disclaimers

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.

Retrieved from "http://www.softwarebyjeff.com/index.php/Simple_unit_testing"

This page has been accessed 872 times. This page was last modified 18:55, 1 Apr 2005.


Find
Browse
Main Page
Community portal
Current events
Recent changes
Random page
Help
Edit
Edit this page
Editing help
This page
Discuss this page
Post a comment
Printable version
Context
Page history
What links here
Related changes
My pages
Create an account or log in
Special pages
New pages
Image list
Statistics
Bug reports
More...