Thursday, January 15, 2009

Getting Started with JUnit

I'm going to skip installation. Eclipse EE has it built in; and you can Google how to install JUnit too.

JUnit makes unit testing of Java classes pretty easy. The idea is to actually write your tests before you start coding based on written specs, but you can also do it afterwards too. Good unit testing should make it easy to change code with confidence. It's also something you can hand to your boss to say "my code works."

Load up Eclipse and make sure the Package Explorer is open.
  • Right Click on a class, then New, JUnit Test Case
  • Make sure the checkboxes for generating setUp and tearDown
Here's how it works:
  • setUp() will be run once at the start of your test. In it you should create an instance of your object. You can declare a variable to hold your object inside the JUnit test case (like private myObjectsName = null).
  • Eclipse automatically makes a stub function for each function in your class-- for example, getName() will have a corresponding testGetName() function
  • You fill out each stub. Remove fail("Not yet implemented") and replace using normal Java code and the macros listed at the following URL (scroll down a bit to all the assert and fail macros):
    http://open.ncsu.edu/se/tutorials/junit/
  • Right click on your JUnitTestCase-- it should be YourObjectNameTest.java-- Run As, JUnit Test (or you can do Debug As instead)
  • The result will be a new pane in Eclipse called JUnit. It will list all the test functions and put an icon next to them indicating if they were successful or if they errored out or failed.
I found assertTrue and assertEquals to be the most useful.

As an example, you could test a get function by using assertEquals to check that the value of the attribute is the same as what you set it to be in Setup. To test a set function, set the value to something else and then assertEquals that the return value is the new value (don't forget to set the value back).

    public void testSetPatientid() {
myObject.setStuff(2); // set a new value
assertEquals("Stuff is incorrect", new Integer(2), (java.lang.Integer) myObject.getStuff()); // check that it's right
myObject.setStuff(1); // set it back
}


Some things are a bit more tricky. For example, I used assertTrue to check that the return of a function was of the right type-- assertTrue("message", myObject.getSomething() instanceof org.blah.blah.Stuff)

For more info, look at:
http://clarkware.com/articles/JUnitPrimer.html

Labels

Blog Archive

Contributors