Nifty JUnit : Working with temporary files

I get this question quite often and I struggled with it many times before: How do I work with temporary files in my JUnit testcases? I would like to explain two simple ways of working with temporary files in JUnit.

1. DeleteOnExit

Create a temporary file with the Java File API and mark it directly as deleteOnExit(). The created file will be deleted when the JVM exits.

2. TemporaryFolder Rule

Use the TemporaryFolder as a Rule in your JUnit Test. TemporaryFolder is an existing Rule from JUnit, see documentation here. The Rule will fire a create() before each test method, which creates a temporary directory. After each test method a delete() method is fired, which deletes the folder and all created files recursively.

Integration testing on REST urls with Spring Boot

We are building a Spring Boot application with a REST interface and at some point we wanted to test our REST interface, and if possible, integrate this testing with our regular unit tests. One way of doing this, would be to @Autowire our REST controllers and call our endpoints using that. However, this won’t give full converage, since it will skip things like JSON deserialisation and global exception handling. So the ideal situation for us would be to start our application when the unit test start, and close it again, after the last unit test.
It just so happens that Spring Boot does this all for us with one annotation: @IntegrationTest.
Here is an example implementation of an abstract class you can use for your unit-tests which will automatically start the application prior to starting your unit tests, caching it, and close it again at the end.

Joy of Coding… and mutation testing in Java

For many years now it has been good practice to write unit tests for your source-code.
And also to use test coverage reporting to see how much of your code is covered by tests.
Although line + branch coverage reporting is quite useful, it doesn’t tell you how good your unit tests actually are.┬áHence it’s even possibly to achieve 100% coverage without even a single assert in your tests.

Being interested in better ways of testing I attended the “Mutation testing” workshop during this years Joy of Coding conference.
Mutation testing is a radical different approach of executing and analyzing the result and coverage of your unit tests. Instead of measuring how much of your code is “accessed from” your unit tests it determines how much of your code is actually “tested by” your unit tests.

Continue reading