我使用的是spring-boot-1.5.10以及spring-security-test & spring-boot-hateoas和JUnit-5。我在单元测试中的application.MockMvc中有一些定制的杰克逊配置,而不是选择那些定制的杰克逊配置。我想知道如何在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);
}
}JACKSON配置类
@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,但是在我的应用程序中,我们使用的是security,所以我想使用web应用程序上下文。
任何帮助或暗示都是值得赞赏的。
发布于 2018-12-10 19:57:16
我将把迄今为止为我所做的工作写在下面。
测试类的注释如下:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {
"app.config1.enable=false"
, "app.xonfig2.enable=false"
})当我想在此测试套件中启用或禁用配置时,这是很有帮助的。为了使其工作,配置类必须包含:
@Configuration
@ConditionalOnProperty(
value = "app.config1.enable", havingValue = "true", matchIfMissing = true
)
public class MyConfig1 {
.
.
.
}将此应用于您的情况,只需启用Jackson配置,它就会工作。如果不希望单独启用配置,请跳过此部分,只添加@SpringBootTest(classes = {MyApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)行。
希望能帮上忙。
https://stackoverflow.com/questions/53711147
复制相似问题