Java – How do I write tests for a simple configuration class?

How do I write tests for a simple configuration class?… here is a solution to the problem.

How do I write tests for a simple configuration class?

Every class in my code needs to be at least 60% tested. I can’t understand how to test a simple configuration class like the following. Can anyone point me in the right direction?

@Configuration
public class JsonConfiguration {

@Bean
   @Primary
   public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
       ObjectMapper objectMapper = builder.build();
       objectMapper.registerModule(new JavaTimeModule());
       return objectMapper;
   }
}

Solution

This problem solves one of the fundamental questions of unit testing: what are we doing and why. Google has a lot to say about this.

I strongly believe that most existing unit test cases are just tests of themselves and consume a lot of resources.

Your code is concise and clear, there really is nothing to test, and you should manage to convince those in power to relax the 60% rule. Thanks for the fact that it is not 90% by the way.

If you can’t relax the 60% rule, you can do at least 3 things:

  1. Try to impress. Write a test that uses 2-3 times the number of lines of code, using mock objects to assert that your code does what it explicitly does. If you change any implementation details of your code, and it doesn’t actually test if your code has the effect you want, you’ll have to change it.

  2. Cheat. Write a test that only asserts anything, but runs the code in the simplest way. Will satisfy the paper pusher and minimize maintenance.

  3. Try writing test code that actually tests that your code does what it is expected at as abstract a level as possible. In your case, you might assert that the objectmapper injected after your code runs actually contains the module. This is harder, it’s really mostly testing the library code, but at least it adds some value.

Related Problems and Solutions