I would like to share a couple of useful tips and links for (unit) testing in Java (focusing on jUnit):
- To have your code testable, it is a good idea to use dependency injection (e.g., all the critical references are passed in the constructor)
- To test such a highly decomposed code, it is very convenient to use some mock-up library. I have been really pleasantly surprised by mockito (https://code.google.com/p/mockito/). It is really easy to create your mocks and the unit tests are then so much easier to write (and can be so much more fine-grained) - I definitely recommend to check it out.
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> </dependency>
- For testing System calls, I like to use SystemRules for jUnit (http://www.stefan-birkner.de/system-rules/)
<dependency> <groupId>com.github.stefanbirkner</groupId> <artifactId>system-rules</artifactId> <version>1.3.1</version> </dependency>
- I am using JUnit Addons (http://junit-addons.sourceforge.net/) for things like
FileAssert(comparing text/binary files with nice reports),
ListAssert(the same for lists).
<dependency> <groupId>junit-addons</groupId> <artifactId>junit-addons</artifactId> <version>1.4</version> lt;/dependency>
- I also use a modification of the
DynamicSuiteclass to invoke all the tests in a package (and sub-packages) (http://www.anzaan.com/2012/01/automatic-unit-testing-test-packages-recursively-in-junit/). Note that I had to fix small bugs in the code before actually using it.