How do I write a test for a simple configuration class?

OneTwo :

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;
   }
}
pvpkiran :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99930&siteId=1