jsonPath在Junit5的Spring Boot中与MockMVC的转换问题

huangapple go评论69阅读模式
英文:

jsonPath cast issue in Junit5 spring boot with MockMVC

问题

我有以下测试案例和导入项

import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.assertj.core.internal.bytebuddy.matcher.ElementMatchers.is;
import static org.mockito.Mockito.doReturn;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@Test
@DisplayName("根据指定的Id返回产品")
void shouldReturnProductBasedOnTheSpecifiedId() throws Exception {
    String Id = java.util.UUID.randomUUID().toString();
    ProductViewModel productViewModel = new ProductViewModel(Id, "Product 1", 100, "Product 1 description", 0);
    doReturn(productViewModel).when(productService).findById(Id);
    mockMvc.perform(get(String.format("/api/v1/product/%s", Id)))

            //验证响应代码和内容类型
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))

            //验证头部
            .andExpect(header().string(HttpHeaders.ETAG, String.format("\"%s\"", Id)))
            .andExpect(header().string(HttpHeaders.LOCATION, String.format("/%s", Id)))

            //验证返回字段
            .andExpect(jsonPath("$.id", is(Id)));
            //.andExpect((ResultMatcher) jsonPath("$.name", is("Product 1")))
            //.andExpect((ResultMatcher) jsonPath("$.price", is(100)))
            //.andExpect((ResultMatcher) jsonPath("$.description", is("Product 1 description")))
            //.andExpect((ResultMatcher) jsonPath("$.version", is(0)));
}

出现错误:

jsonPath在Junit5的Spring Boot中与MockMVC的转换问题

如果我对对象进行类型转换,会收到类型转换错误消息。

jsonPath在Junit5的Spring Boot中与MockMVC的转换问题

英文:

I have the below test case with imports as

import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.assertj.core.internal.bytebuddy.matcher.ElementMatchers.is;
import static org.mockito.Mockito.doReturn;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
      @Test
            @DisplayName("Should return product based on the specified Id")
            void shouldReturnProductBasedOnTheSpecifiedId() throws Exception {
                String Id = java.util.UUID.randomUUID().toString();
                ProductViewModel productViewModel = new ProductViewModel(Id, "Product 1", 100, "Product 1 description", 0);
                doReturn(productViewModel).when(productService).findById(Id);
                mockMvc.perform(get(String.format("/api/v1/product/%s", Id)))
    
                        //Validate the response code and content type
                        .andExpect(status().isOk())
                        .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
    
                        //validate the headers
                        .andExpect(header().string(HttpHeaders.ETAG, String.format("\"%s\"", Id)))
                        .andExpect(header().string(HttpHeaders.LOCATION, String.format("/%s", Id)))
    
                        //Validate the return fields
                        .andExpect(jsonPath("$.id", is(Id)));
                        //.andExpect((ResultMatcher) jsonPath("$.name", is("Product 1")))
                        //.andExpect((ResultMatcher) jsonPath("$.price", is(100)))
                        //.andExpect((ResultMatcher) jsonPath("$.description", is("Product 1 description")))
                        //.andExpect((ResultMatcher) jsonPath("$.version", is(0)));
    
            }

Getting an error as

jsonPath在Junit5的Spring Boot中与MockMVC的转换问题

If I cast the object I get an cast error message.

jsonPath在Junit5的Spring Boot中与MockMVC的转换问题

答案1

得分: 2

有几种方法可以解决这个问题:

## 包括单个 Json 属性的比较 ##

```java
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.core.Is.is;

mockMvc.perform(get(String.format("/api/v1/product/%s", Id))
       .andExpect(content().contentType(APPLICATION_JSON_VALUE))
       .andExpect(jsonPath("$.id", is(Id))));

与你的示例不同之处在于 "is import"


将 Json 响应反序列化为类并比较对象

这是一种更通用且可重复使用的方法。

  1. 使用 Json 反序列化方法将其转换为一个已知类实例的对象。
  2. 在测试中比较预期对象与接收到的对象。

你可以在以下 链接 中看到完整的示例,更具体地在测试中:

static Stream<Arguments> findByIdWithOrderLines_validIdTestCases() {
  PizzaDto pizzaDto = new PizzaDto((short)1, "Carbonara", 7.50);
  OrderLineDto orderLineDto = new OrderLineDto(10, 1, pizzaDto, (short)2, 15D);
  OrderDto dto = new OrderDto(1, "Order 1", new Date(), asList(orderLineDto));
  return Stream.of(
      //@formatter:off
      //            serviceResult,   expectedResultHttpCode,   expectedBodyResult
      Arguments.of( empty(),         NOT_FOUND,                null ),
      Arguments.of( of(dto),         OK,                       dto )
  ); //@formatter:on
}

@ParameterizedTest
@SneakyThrows
@WithMockUser(authorities = {Constants.ROLE_ADMIN})
@MethodSource("findByIdWithOrderLines_validIdTestCases")
@DisplayName("findByIdWithOrderLines: 给定 Id 验证验证,然后返回适当的 Http code")
public void findByIdWithOrderLines_whenGivenIdVerifiesValidations_thenSuitableHttpCodeIsReturned(Optional<OrderDto> serviceResult,
                                      HttpStatus expectedResultHttpCode, OrderDto expectedBodyResult) {
    // Given
    Integer validOrderId = 1;

    // When
    when(mockOrderService.findByIdWithOrderLines(validOrderId)).thenReturn(serviceResult);

    ResultActions result = mockMvc.perform(get(RestRoutes.ORDER.ROOT + "/" + validOrderId + RestRoutes.ORDER.WITH_ORDERLINES));

    // Then
    result.andExpect(status().is(expectedResultHttpCode.value()));
    assertEquals(expectedBodyResult, fromJson(result.andReturn().getResponse().getContentAsString(), OrderDto.class));
    verify(mockOrderService, times(1)).findByIdWithOrderLines(validOrderId);
}

<details>
<summary>英文:</summary>
There are several ways to solve it:
## Include individual Json properties comparison ##
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.core.Is.is;
mockMvc.perform(get(String.format(&quot;/api/v1/product/%s&quot;, Id))
.andExpect(content().contentType(APPLICATION_JSON_VALUE))
.andExpect(jsonPath(&quot;$.id&quot;, is(Id)));
The difference with your example is on **&quot;is import&quot;**.
----------
## Deserialize Json response into a class and compare objects ##
This is a more generic and reusable approach.
1. Use a Json deserialize method to convert that one into an object of a well-known class instance.
2. Compare expected object with the received one in the test.
You can see a complete example of it in the following 
[1], more specifically in the test: static Stream&lt;Arguments&gt; findByIdWithOrderLines_validIdTestCases() { PizzaDto pizzaDto = new PizzaDto((short)1, &quot;Carbonara&quot;, 7.50); OrderLineDto orderLineDto = new OrderLineDto(10, 1, pizzaDto, (short)2, 15D); OrderDto dto = new OrderDto(1, &quot;Order 1&quot;, new Date(), asList(orderLineDto)); return Stream.of( //@formatter:off // serviceResult, expectedResultHttpCode, expectedBodyResult Arguments.of( empty(), NOT_FOUND, null ), Arguments.of( of(dto), OK, dto ) ); //@formatter:on } @ParameterizedTest @SneakyThrows @WithMockUser(authorities = {Constants.ROLE_ADMIN}) @MethodSource(&quot;findByIdWithOrderLines_validIdTestCases&quot;) @DisplayName(&quot;findByIdWithOrderLines: when given Id verifies the validations then the suitable Http code is returned&quot;) public void findByIdWithOrderLines_whenGivenIdVerifiesValidations_thenSuitableHttpCodeIsReturned(Optional&lt;OrderDto&gt; serviceResult, HttpStatus expectedResultHttpCode, OrderDto expectedBodyResult) { // Given Integer validOrderId = 1; // When when(mockOrderService.findByIdWithOrderLines(validOrderId)).thenReturn(serviceResult); ResultActions result = mockMvc.perform(get(RestRoutes.ORDER.ROOT + &quot;/&quot; + validOrderId + RestRoutes.ORDER.WITH_ORDERLINES)); // Then result.andExpect(status().is(expectedResultHttpCode.value())); assertEquals(expectedBodyResult, fromJson(result.andReturn().getResponse().getContentAsString(), OrderDto.class)); verify(mockOrderService, times(1)).findByIdWithOrderLines(validOrderId); } [1]: https://github.com/doctore/Spring5Microservices/blob/master/order-service/src/test/java/com/order/controller/OrderControllerTest.java </details>

huangapple
  • 本文由 发表于 2020年8月30日 01:09:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63649712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定