JUnit如何与WebApplication上下文一起在MockMvc中配置Jackson

时间:2018-12-10 17:58:20

标签: java spring junit spring-security mockito

我正在使用 spring-boot-1.5.10 以及 spring-security-test spring-boot-hateoas JUnit-5 。我的应用程序中有一些自定义的Jackson配置。在单元测试中,MockMvc没有选择那些自定义的Jackson配置。我想知道如何在MockMvc中注入那些配置,以及我想知道如何在MockMvc中注入定制的Jackson模块。请找到以下代码以供参考,

@RunWith(SpringRunner.class)
@WebMvcTest(BookController.class)
public class BookControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;

    @MockBean
    private BookService bookService;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(SecurityMockMvcConfigurers.springSecurity()) //Here i would also like to configure Jackson
                .build();
    }

    @Test
    @WithMockApiUser(roles = {"API_ADMIN"})
    public void shouldGetBook() throws Exception {
        BookResponse bookResponse = BookResponse.builder()
                .basicInfo(getBasicInfo())
                .extendedInfo(getExtendedInfo())
                .build();
        given(bookService.getBook(apiAuthentication.getApiContext(),"bookUid")).willReturn(bookResponse);
        System.out.println("Input ::"+objectMapper.writeValueAsString(bookResponse)); //Here the json string response looks fine.
        MvcResult result = mockMvc.perform(get("/v1/books/bookUid"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/hal+json"))
                .andExpect(jsonPath("bookUid").value("bookUid")).andReturn();
        System.out.println("response::"+objectMapper.writeValueAsString(result.getResponse().getContentAsString()));  //Here the content string is not properly converted by Jackson
        verifyNoMoreInteractions(bookService);
    }
}

杰克逊配置课程

@Configuration
public class ObjectMapperConfiguration {

  @Autowired
  private ObjectMapper objectMapper;

  @PostConstruct
  public void init() {
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  }

}

我已经搜索过这个问题,但是所有链接都使用 StandaloneSetUp ,但是在我的应用程序中,我们使用的是spring-security,因此我想使用Web应用程序上下文。

任何帮助或提示都是有意义的。

1 个答案:

答案 0 :(得分:0)

我将在下面发布到目前为止为我工作的内容。

测试类带有以下注释:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {
    "app.config1.enable=false"
    , "app.xonfig2.enable=false"
})

当我想在此测试套件中启用或禁用配置时,这很有用。为了使它起作用,Configuration类必须包含:

@Configuration
@ConditionalOnProperty(
    value = "app.config1.enable", havingValue = "true", matchIfMissing = true
)
public class MyConfig1 {
     .
     .
     .
}

在您的情况下应用此功能,只需启用Jackson配置即可。如果您不想单独启用配置,请跳过此部分,仅添加@SpringBootTest(classes = {MyApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)行。

希望对您有帮助。