Rest Assured Mock Mvc没有拿起自定义Object Mapper

时间:2018-03-16 12:42:15

标签: java spring-mvc rest-assured

我对这篇文章有一个非常类似的问题:Rest Assured doesn't use custom ObjectMapper

但是,我使用的配置/模型略有不同,所提供的答案并没有解决我的问题。

运行模拟mvc测试时,我的自定义ObjectMapper配置没有被提取。我已经尝试将此配置类附加到RestAssuredMockMvc,但是当独立安装程序触发时,它似乎仍然没有选择它。

有什么想法吗?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public abstract class BaseClassForContractTests {

@Autowired
Controller controller;

@Before
public void setup() {

    RestAssuredMockMvc.config = RestAssuredMockMvcConfig.config().objectMapperConfig(
            ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory(new Jackson2ObjectMapperFactory() {
                @SuppressWarnings("rawtypes")
                @Override
                public ObjectMapper create(Class cls, String charset) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.registerModule(new JavaTimeModule());
                    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
                    //objectMapper.setTimeZone(TimeZone.getTimeZone("America/New_York"));
                    //objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, true);
                    return objectMapper;
                }
            })
    );

    RestAssuredMockMvc.standaloneSetup(controller);

}

}

2 个答案:

答案 0 :(得分:1)

是的,这是愚蠢/简单的事。如果有人遇到这个问题而没有配置,那么你应该使用RestAssuredMockMvc。 webAppContextSetup (context);而不是standaloneSetup。您所要做的就是@Autowire webAppContext。

答案 1 :(得分:-1)

我有RestAssuredMockMvc.standaloneSetup的安装对象映射器,对我有用。

MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new
MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setObjectMapper(new ObjectMapper()));
RestAssuredMockMvc.standaloneSetup(
     MockMvcBuilders.standaloneSetup(yourcontroller)
             .setMessageConverters(mappingJackson2HttpMessageConverter)
);

The full solution is described in this article