Rest Assured不使用自定义ObjectMapper [英] Rest Assured doesn't use custom ObjectMapper

查看:372
本文介绍了Rest Assured不使用自定义ObjectMapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rest Assured为我的Spring Boot项目进行Controller测试。我们在序列化对象上使用Java 8 ZonedDateTime字段,在序列化中使用Jackson 2。运行项目时,序列化按预期工作,但运行Rest Assured测试时,日期未正确序列化。我知道Rest Assured使用自己的ObjectMapper配置,但我的问题是无论我做什么, Rest Assured似乎忽略了我的ObjectMapper配置。

I'm making Controller tests for my Spring Boot project using Rest Assured. We are using Java 8 ZonedDateTime fields on our serialized objects and Jackson 2 for our serialization. When running the project, serialization works as expected, but when running Rest Assured tests, the dates are not serializing correctly. I understand that Rest Assured uses its own ObjectMapper config, but my problem is that no matter what I do, Rest Assured appears to be ignoring my ObjectMapper configuration.

以下是我测试的相关部分:

Here are the relevant parts of my test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes=MyApplication.class)
@WebAppConfiguration
@Transactional
public class MAppControllerTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {

        RestAssured.config = RestAssuredConfig.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.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 
                    objectMapper.setTimeZone(TimeZone.getTimeZone("America/New_York"));
                    objectMapperconfigure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, true);
                    return objectMapper; 
                  } 
            })
         );

        mockMvc = MockMvcBuilders.webAppContextSetup(context)
            .apply(springSecurity())
            .build();
    }

    @Test
    @WithMockUser(roles = {"APP_ADMIN"}, username = "TEST_USER")
    @Sql(scripts = "/db-scripts/test-data.sql")
    public void testCreateItem() {
        Item postBody = new Item();
        postBody.setDate(ZonedDateTime.now());

        Item result =
        given().
            mockMvc(mockMvc).
            contentType(ContentType.JSON).
            body(postBody).
            log().all().
        when().
            post("/items").
        then().
            log().all().
            statusCode(201).
            body(matchesJsonSchemaInClasspath("json-schemas/item.json")).
            extract().as(Item.class);

        assertThat(result.getDate(), equalTo(postBody.getDate());
    }

Item.class:

Item.class:

@Data
@Entity
@Table(name = "ITEM", schema = "MY_APP")
@EqualsAndHashCode(of = "id")
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Item implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ITEM_ID_SEQ")
    @SequenceGenerator(name = "ITEM_ID_SEQ", sequenceName = "MY_APP.ITEM_ID_SEQ")
    private Long id;

    @Column(name = "DATE")
    private ZonedDateTime date;
}

我们正在使用spring-boot-starter-data-jpa,因此我们只声明了一个扩展的ItemRepository接口CrudRepository(Item,Long)(我这里只使用括号,因为堆栈溢出不喜欢尖括号)并且控制器调用服务调用内置的save方法来保存Item并返回持久化的Item,所以在我的测试中,我希望我发送的日期在返回时保存为相同的。

We're using spring-boot-starter-data-jpa, so we just declared an ItemRepository interface that extends CrudRepository(Item, Long) (I just used parenthesis here because stack overflow didn't like the angle brackets) and the controller calls the service which calls the built in save method to persist the Item and returns the persisted Item, so in my test, I'm expecting the date I sent in to be saved to be the same when it's returned.

我遇到的主要问题是返回的日期是GMT,而我的期望是它将在EST / EDT中,因此断言失败,因为ZonedDateTime.now()使用了当地时区,但无论出于何种原因,Rest Assured在某个地方,将时区更改为GMT:

The main problem I'm having is that the returned date is in GMT, whereas my expectation is that it'll be in EST/EDT, and thus the assertion fails because ZonedDateTime.now() uses the local time zone, but for whatever reason, Rest Assured is, somewhere along the line, changing the time zone to GMT:

java.lang.AssertionError:
Expected: <2017-03-30T14:53:19.102-04:00[America/New_York]>
but: was <2017-03-30T18:53:19.102Z[GMT]>

还有一个日期甚至没有被序列化为ISO,而是一个奇怪的小数。不知道那个是什么,但是当项目运行时它不会发生;这些问题都没有。只有当Rest Assured测试运行时才会这样。

There's also one date that's not even getting serialized as an ISO, but as a weird decimal. No idea what's up with that one, but it doesn't happen when the project is running; neither of these problems do. It's only when Rest Assured tests are run.

无论我将ObjectMapper配置为我的测试setUp,我都会收到此错误...无论我是否即使有一个ObjectMapper,它也会被完全忽略。

I'm getting this error no matter what I configure the ObjectMapper to be in my test setUp... Regardless of whether I even HAVE an ObjectMapper there or not, it's getting completely ignored.

相关技术版本:


  • Spring Boot:1.5.2.RELEASE

  • com.fasterxml.jackson.core:jackson-databind:2.6.4

  • com .fasterxml.jackson.core:jackson-annotations:2.6.4

  • com.fasterxml.jackson.core:jackson-core:2.6.4

  • com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.6.4

  • com.jayway.restassured:rest-assured:2.9.0

  • com.jayway.restassured:json-schema-validator:2.9.0

  • com.jayway.restassured:spring-mock-mvc:2.9.0

  • Spring Boot: 1.5.2.RELEASE
  • com.fasterxml.jackson.core:jackson-databind: 2.6.4
  • com.fasterxml.jackson.core:jackson-annotations: 2.6.4
  • com.fasterxml.jackson.core:jackson-core: 2.6.4
  • com.fasterxml.jackson.datatype:jackson-datatype-jsr310: 2.6.4
  • com.jayway.restassured:rest-assured: 2.9.0
  • com.jayway.restassured:json-schema-validator: 2.9.0
  • com.jayway.restassured:spring-mock-mvc: 2.9.0

推荐答案

你不应该使用 RestAssured.config 和<使用RestAssured和MockMvc时code> RestAssuredConfig 。而是使用 io.restassured.module.mockmvc.RestAssuredMockMvc io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig 。即替换你的代码:

You shouldn't use RestAssured.config and RestAssuredConfig when using RestAssured with MockMvc. Instead use io.restassured.module.mockmvc.RestAssuredMockMvc and io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig. I.e. replace your code:

RestAssured.config = RestAssuredConfig.config().objectMapperConfig(
   ...
);

with:

RestAssuredMockMvc.config = RestAssuredConfigMockMvc.config().objectMapperConfig(
    ...
);

这篇关于Rest Assured不使用自定义ObjectMapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆