如何在 REST Assured 中访问底层 Jackson ObjectMapper?

2022-09-01 22:39:47

我需要在 REST Assured 中配置底层 Jackson ObjectMapper。我正在使用 REST Assured 编写 REST API 测试,我需要定义一些过滤器来注册到用于将我的对象序列化为 JSON 的 ObjectMapper:

    String newTestSuite = "{\"name\":\"Added through Rest API\",\"description\":\"Test Description\",\"steps\":[]}";

    FilterProvider filters = new SimpleFilterProvider().addFilter("createNewTestSuite", new NewTestSuiteFilter());
    ObjectMapper om = new ObjectMapper();
    om.setFilters(filters);

    try {
        TestSuite ts = om.readValue(newCaspianTest, TestSuite.class);

        RequestSpecification requestSpec = new RequestSpecBuilder()
            .setBaseUri("https://somesite.com")
            .setBody(ts)
            .setUrlEncodingEnabled(false)
            .build();

        ResponseSpecification responseSpec = new ResponseSpecBuilder()
            .expectStatusCode(200)
            .expectStatusLine(Matchers.containsString("200 OK"))
            .build();

        RestAssured.given()
            .auth().basic("testUser","testPassword")
            .spec(requestSpec)
            .log().all()
            .post("/restendpoint")
                .then()
                .log().all()
                .spec(responseSpec);

    } catch(JsonParseException jpe) {

    } catch(JsonMappingException jme) {

    } catch(IOException ioe) {

    }
}

}


答案 1

你可以试试这个:

RestAssured.config = RestAssuredConfig.config().objectMapperConfig(new ObjectMapperConfig().jackson2ObjectMapperFactory(
new Jackson2ObjectMapperFactory() {
        @Override
        public ObjectMapper create(Class aClass, String s) {
            FilterProvider filter = new SimpleFilterProvider().addFilter(...);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setFilters(filter);
            return objectMapper;
        }
    }
));

答案 2

这将为您提供一个对象映射器,当后端开发人员决定添加新字段时,该对象映射器不会爆炸。

RestAssured.config = RestAssuredConfig.config().objectMapperConfig(new ObjectMapperConfig().jackson2ObjectMapperFactory(
    new Jackson2ObjectMapperFactory() {
      @Override
      public ObjectMapper create(Type cls, String charset) {
        ObjectMapper om = new ObjectMapper().findAndRegisterModules();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return om;
      }          

    }
));

推荐