使用Spring Rest Docs在Junit中测试用例失败

如何解决使用Spring Rest Docs在Junit中测试用例失败

我已经实现了一个示例应用程序,并通过将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$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));
    }
}

解决方法

您在ProductControllerTest中正在使用

@MockBean private ProductService productService;

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

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

看看here以获得更多示例。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?