0

Note that this is not the same issues as in Customized ObjectMapper not used in test, which is about importing a programmatically configured ObjectMapper.

I want to have a single source of truth for the configuration of the ObjectMapper, and the logical place to do that is the spring application.yml via the spring.jackson properties. I can't figure out how to apply that configuration though. I'm using a simple @ExtendWith(SpringExtension.class) annotation on my JUnit5 tests.

I've tried @AutoConfigureJsonTesters, @Import(JacksonAutoConfiguration.class) and @ContextConfiguration(classes = JacksonAutoConfiguration.class), to no avail.

Michael Böckling
  • 7,341
  • 6
  • 55
  • 76
  • Have you already configured that for you default application configuration? How does it look like? Have you used any custom profiles? Do you have any custom *application.yml* configuration file for your test runtime? Please add all the relevant parts of your application. – tmarwen Jun 09 '20 at 13:08

1 Answers1

1

You can autowire ObjectMapper in your test class as used below

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
class MyIntegrationTest {

  @Autowired
  private MockMvc mockMvc;

  @Autowired
  private ObjectMapper objectMapper;

  @Autowired
  private UserRepository userRepository;

  @Test
  void testCreate() throws Exception {
    User user = new Usere(“ahhi”, “abhi@gmail.com”);

    mockMvc.perform(post("/register/user")
            .contentType("application/json")
            .param("sendWelcomeMail", "true")
            .content(objectMapper.writeValueAsString(user)))
            .andExpect(status().isOk());

    UserEntity userEntity = userRepository.findByName("ahhi");
    assertThat(userEntity.getEmail()).isEqualTo("abhi@gmail.com");
  }
}
abhinav kumar
  • 1,487
  • 1
  • 12
  • 20
  • 2
    The key is to use `@SpringBootTest(classes = JacksonAutoConfiguration.class)`, then the correctly configured Jackson ObjectMapper is used. Maybe you can amend your answer. – Michael Böckling Jun 09 '20 at 13:42