Skip to main content

Testing in Java

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 DynamicSuite class 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.

Comments

Post a Comment

Popular posts from this blog

Running a GroovyFX application from Ant

Althoug an extremely efficient for implementation of UI in Java, GroovyFX (the Groovy wrapper for JavaFX 2.0) is hard to run on command line (e.g., via Ant).
The only straightforward way of running it I was able to find is just to compile all the Groovy sources using groovyc Ant task and then to run the Java class corresponding to the main Groovy script. In this case, all the Groovy jars, the JavaFX runtime jar, and the GroovyFX jar have to be on the classpath.
Moreover, it is extremely important that you run the final Java task using fork=”true”, otherwise you will get strange exceptions from the JavaFX runtime.
For a practical example of the Ant script running such an application, see the build.xml at https://github.com/keznikl/GDeeco/blob/master/build.xml.
I wasn’t able to make it work just by running it as a regular groovy script (without compilation etc.).
What is your experience?