Сбой тестового примера в Junit с документами Spring Rest

#java #spring-boot #junit #spring-restdocs

#java #spring-boot #junit #spring-restdocs

Вопрос:

Я реализовал образец приложения и протестировал его с помощью JUnit с документами spring rest. Когда я выполняю вызов Rest API через postman, результат извлекается успешно, и когда я делаю то же самое с помощью письменного тестового примера, данные не извлекаются.

Тестовый пример завершается ошибкой со следующей ошибкой

 java.lang.AssertionError: []: Expected 2 values but got 0

    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:417)
    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:394)
    at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:336)
    at org.springframework.test.util.JsonExpectationsHelper.assertJsonEqual(JsonExpectationsHelper.java:61)
    at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$json$9(ContentResultMatchers.java:215)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at com.benz.demo.web.controller.ProductControllerTest.getEmployees(ProductControllerTest.java:67)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
  

Класс контроллера

 @RestController
@RequestMapping("/products")
public class ProductController {

private ProductService productService;

    @Autowired
    private ProductController(ProductService productService)
    {
        this.productService=productService;
    }

@GetMapping
    public ResponseEntity<List<Product>> getAllProduct()
    {
        return ResponseEntity.ok(productService.getAllProduct());
    }
}
  

Класс обслуживания

 @Service
public class ProductServiceImpl implements ProductService {

    @Override
    public List<Product> getAllProduct() {
        return getProducts();
    }

    private List<Product> getProducts()
    {
        Product product_1=new Product();
        product_1.setProductId(1001);
        product_1.setProductName("Penguin-ears");
        product_1.setNumberOfUnitInCartoon(20);
        product_1.setPriceOfCartoon(175.00);
        product_1.setUrlOfImage("https://i.ibb.co/pLdM7FL/shutterstock-306427430-scaled.jpg");

        Product product_2=new Product();
        product_2.setProductId(1002);
        product_2.setProductName("Horseshoe");
        product_2.setNumberOfUnitInCartoon(5);
        product_2.setPriceOfCartoon(825);
        product_2.setUrlOfImage("https://i.ibb.co/MRDwnqj/horseshoe.jpg");


        return new ArrayList<>(Arrays.asList(product_1,product_2));
    }
}
  

Тестовый класс контроллера

 @ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@WebMvcTest
public class ProductControllerTest {


    @Autowired
    private WebApplicationContext webApplicationContext;


    @MockBean
    private ProductService productService;


    private MockMvc mockMvc;

    List<Product> products =null;

    @BeforeEach
    public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider documentationContextProvider) {
        this.mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(MockMvcRestDocumentation.documentationConfiguration(documentationContextProvider))
                .build();

        products=getProducts();
    }

    @Test
    public void getEmployees() throws Exception {

        String expectedProduct=new ObjectMapper().writeValueAsString(products);

        MvcResult result= mockMvc.perform(get("/products")
                .contentType(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isOk())
                .andExpect(content().json(expectedProduct))
                .andReturn();

        String actualProduct=result.getResponse().getContentAsString();

        Assertions.assertEquals(expectedProduct,actualProduct);

    }

    private List<Product> getProducts()
    {
        Product product_1=new Product();
        product_1.setProductId(1001);
        product_1.setProductName("Penguin-ears");
        product_1.setNumberOfUnitInCartoon(20);
        product_1.setPriceOfCartoon(175.00);
        product_1.setUrlOfImage("https://i.ibb.co/pLdM7FL/shutterstock-306427430-scaled.jpg");

        Product product_2=new Product();
        product_2.setProductId(1002);
        product_2.setProductName("Horseshoe");
        product_2.setNumberOfUnitInCartoon(5);
        product_2.setPriceOfCartoon(825);
        product_2.setUrlOfImage("https://i.ibb.co/MRDwnqj/horseshoe.jpg");


        return new ArrayList<>(Arrays.asList(product_1,product_2));
    }
}
  

Ответ №1:

В вашем ProductControllerTest вы используете

@MockBean private ProductService productService;

Но вы не указываете макетному компоненту, как он должен вести себя, когда контроллер его вызовет.

Вам нужно добавить что-то вроде when(productService.getAllProduct()).thenReturn(new LinkedList(...));

Посмотрите здесь больше примеров.