集成测试中 MockMvc 和 RestTemplate 的区别

新手上路,请多包涵

MockMvcRestTemplate 都用于与 Spring 和 JUnit 的集成测试。

问题是:它们之间有什么区别,什么时候我们应该选择一个而不是另一个?

以下是两种选择的示例:

 //MockMVC example
mockMvc.perform(get("/api/users"))
            .andExpect(status().isOk())
            (...)

//RestTemplate example
ResponseEntity<User> entity = restTemplate.exchange("/api/users",
            HttpMethod.GET,
            new HttpEntity<String>(...),
            User.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());

原文由 Denis C de Azevedo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 731
2 个回答

本文 所述,当您要测试应用程序的 服务器端 时,您应该使用 MockMvc

Spring MVC 测试建立在来自 spring-test 的模拟请求和响应之上,不需要运行的 servlet 容器。主要区别在于实际的 Spring MVC 配置是通过 TestContext 框架加载的,并且请求是通过实际调用 DispatcherServlet 以及在运行时使用的所有相同的 Spring MVC 基础设施来执行的。

例如:

 @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("servlet-context.xml")
public class SampleTests {

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Before
  public void setup() {
    this.mockMvc = webAppContextSetup(this.wac).build();
  }

  @Test
  public void getFoo() throws Exception {
    this.mockMvc.perform(get("/foo").accept("application/json"))
        .andExpect(status().isOk())
        .andExpect(content().contentType("application/json"))
        .andExpect(jsonPath("$.name").value("Lee"));
  }}

RestTemplate 当你想测试 Rest 客户端 应用程序时你应该使用:

如果您有使用 RestTemplate 的代码,您可能想要测试它并且您可以针对正在运行的服务器或模拟 RestTemplate。客户端 REST 测试支持提供了第三种选择,即使用实际的 RestTemplate 但使用自定义配置它 ClientHttpRequestFactory 根据实际请求检查预期并返回存根响应。

例子:

 RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);

mockServer.expect(requestTo("/greeting"))
  .andRespond(withSuccess("Hello world", "text/plain"));

// use RestTemplate ...

mockServer.verify();

也阅读 这个例子

原文由 nivash 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 MockMvc ,您通常会设置整个 Web 应用程序上下文并模拟 HTTP 请求和响应。因此,虽然一个假的 DispatcherServlet 启动并运行,模拟您的 MVC 堆栈将如何运行,但没有建立真正的网络连接。

使用 RestTemplate ,您必须部署一个实际的服务器实例来侦听您发送的 HTTP 请求。

原文由 Sotirios Delimanolis 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题