Junit 中的测试用例失败 Spring Rest Docs

Test Case Fail in Junit with Spring Rest Docs

我已经实现了一个示例应用程序,并使用 JUnit 和 spring rest 文档对其进行了测试。当我通过邮递员进行 Rest API 调用时,结果被成功检索,当我通过书面测试用例做同样的事情时,数据没有检索到。

测试用例失败并出现以下错误

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(ContentResultMatchers.java:215)
    at org.springframework.test.web.servlet.MockMvc.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[=11=](ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke[=11=](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(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(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(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(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)

控制器class

@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());
    }
}

服务class

@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));
    }
}

控制器测试Class

@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));
    }
}

在您的ProductControllerTest中您正在使用

@MockBean private ProductService productService;

但是您没有指定模拟 bean 在控制器调用它时应该如何表现。

您需要添加类似 when(productService.getAllProduct()).thenReturn(new LinkedList(...));

查看 here 了解更多示例。