集成测试中MockMvc和RestTemplate之间的区别

集成测试中MockMvc和RestTemplate之间的区别

本文介绍了集成测试中MockMvc和RestTemplate之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和用于Spring和JUnit的集成测试。

Both MockMvc and RestTemplate are used for integration tests with Spring and JUnit.

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

Question is: what's the difference between them and when we should choose one over another?

这里只是两个选项的例子:

Here are just examples of both options:

//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());


推荐答案


你应该使用的文章 MockMvc 当你想测试应用程序的服务器端时:

As said in thisarticle you should use MockMvc when you want to test Server-side of application:

例如:

@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().mimeType("application/json"))
        .andExpect(jsonPath("$.name").value("Lee"));
  }}

RestTemplate 你应该在你想要测试休息客户端应用程序时使用:

And RestTemplate you should use when you want to test Rest Client-side application:

示例:

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

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

// use RestTemplate ...

mockServer.verify();

也读

这篇关于集成测试中MockMvc和RestTemplate之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:26