Thursday, 24 March 2011

JUnit 4 (in Eclipse)

I'm sure this will be second nature in no time at all, but there are some fairly major differences between the way JUnit worked in version 3 compared to version 4, so I thought I'd write down what I've done and what I need to look into doing in the future.

In JUnit 4 you no longer have to extend any classes. The tests are identified by annotations. You do still need to import a load of JUnit classes to get the annotations and assertions right though.

So, I create my test classes in a test package that mirrors the name of the package under test with 'test' added to the end. I keep my test code in a second source file, called 'test' (to do this in Eclipse right-click on the project, go to properties, Java Build Path, Source, Add folder). My test classes are named after the class they are testing, again with the word 'Test' added to the end. This lets me reflect the same structure in the tests as the main code, so I can find things more easily.

If you are writing the tests after the class, you can choose which of the class methods you want to auto-generate code for. If you are writing the tests first, obviously this isn't available! I do a bit of both, depending on how good I'm feeling.

I haven't really been using anything other than that. To run the tests, I right-click on the test class in Eclipse, and choose Run as -> JUnit test. Eclipse then gives me a lovely interface that either shows a green bar if everything passes, or a red bar and a list of failures. Clicking on the failure takes me to the assertion that failed, so I can identify the exact test that failed. I haven't got into test suites yet, or using the @before or @after annotations.

One thing I think I do need to look into is the use of 'mock objects', particularly where my code is using SmartFox. My request handlers could do with testing, and I think this is the best way. At the moment I've limited myself to testing only my model, which is not great. It's a start, at least!

No comments:

Post a Comment