哪个是对Spring Boot Rest API进行端到端测试的最佳方法?

时间:2018-06-15 16:40:40

标签: spring-boot junit spring-boot-test

我已经检查了google和stackoverflow以进行Spring Boot Rest API的端到端测试。

我想测试控制器 - >服务 - >存储库一次。

我发现两种方法都很有效:

1. TestRestTemplate: 
   Single call to the controller method with in-memory database configuration for repository.
2. MockMvc: 
   Create 2 Test classes. 
   one for Controller->Service 
   and one for Service->Repository. 
   Is there any way to club both 2 classes into one class.

这是最好的方式"端到端测试" Spring Boot Rest API来自2个以上的方法???

1 个答案:

答案 0 :(得分:1)

我想说更好的方法来进行 END2END 测试是使用TestRestTemplate。它实际上会在一个随机端口(你配置它)启动服务器并调用api本身进行测试。这样,它模仿正在运行的服务器的实际行为并使用默认的配置和bean。

MockMvc,在我的测试经验中,主要用于测试web层,即控制器。我会使用模拟的服务bean来替换原来的。所以我可以测试控制器层本身的行为,而不必担心服务层中的错误。更重要的是,我不必在测试之前设置任何数据库。

所以我想说,对于E2E测试,你可以选择第一种方法。