Reputation: 2483
Every class in my code needs to be at least 60% tested. I'm having trouble understanding how to test simple configuration classes like the one below. 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;
}
}
Upvotes: 3
Views: 328
Reputation: 871
This question addresses one of the fundamental problems of unit testing: What are we doing and why. Google has a lot to say about this.
I am firmly convinced that most existing unit test cases test nothing more than them selves and are a huge ressource drain.
Your code is clear and concise and really has nothing to test, and you should try to convince the powers that be to relax the 60% rule. Be grateful that it is not 90% btw.
If you can not have the 60% rule relaxed you can do at least 3 things:
Try to impress. Write a test that uses 2-3 times as many lines as your code, using mock objects that asserts that your code does what it clearly does. You will have to change it if you ever change any implementation details of your code and it really does not test that your code has the effect you intend.
Cheat. Write a test that asserts nothing but runs the code in the easiest way possible. Will satisfy paper pushers and minimize maintenance.
Try to write test code that actually tests that your code does what it is intended to at the most abstract level you can. In your case that might be asserting that an injected objectmapper actually contains the module after your code is run. This is harder and really mostly tests library code, but at least it adds some value.
Upvotes: 2
Reputation: 27048
This should be able to do it
@RunWith(MockitoJUnitRunner.class)
public class JsonConfigurationTest {
@Mock
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;
@Mock
ObjectMapper objectMapper;
@Test
public void testObjectMapper() {
JsonConfiguration jsonConfiguration = new JsonConfiguration();
doAnswer(invocation -> objectMapper).when(jackson2ObjectMapperBuilder).build();
ArgumentCaptor<Module> moduleArgumentCaptor = ArgumentCaptor.forClass(Module.class);
doAnswer(invocation -> {
Module value = moduleArgumentCaptor.getValue();
assertTrue(value instanceof JavaTimeModule);
return objectMapper;
}).when(objectMapper).registerModule(moduleArgumentCaptor.capture());
jsonConfiguration.objectMapper(jackson2ObjectMapperBuilder);
verify(objectMapper, times(1)).registerModule(any(Module.class));
}
}
using ArgumentCaptor
you can basically assert the right module is being registered. And using verify
you are making sure that registerModule is called once.
Upvotes: 1