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

Den*_*edo 45 java junit spring integration-testing spring-mvc

无论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());
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 37

有了MockMvc,你通常建立一个完整的web应用程序上下文和嘲讽的HTTP请求和响应.因此,虽然虚假DispatcherServlet启动并运行,模拟MVC堆栈的运行方式,但没有真正的网络连接.

使用RestTemplate,您必须部署实际的服务器实例以侦听您发送的HTTP请求.


niv*_*ash 33

正如在说这个 文章你应该使用MockMvc时要测试服务器端应用程序:

Spring MVC Test构建在模拟请求和响应之上,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().mimeType("application/json"))
        .andExpect(jsonPath("$.name").value("Lee"));
  }}
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

还读了这个例子


Mic*_*ing 17

可以使用RestTemplate和MockMvc!

如果您有一个单独的客户端,您已经将Java对象的冗长映射到URL并转换为Json和从Json进行转换,并且您希望将其重用于MockMVC测试,那么这非常有用.

这是怎么做的:

@RunWith(SpringRunner.class)
@ActiveProfiles("integration")
@WebMvcTest(ControllerUnderTest.class)
public class MyTestShould {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void verify_some_condition() throws Exception {

        MockMvcClientHttpRequestFactory requestFactory = new MockMvcClientHttpRequestFactory(mockMvc);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        ResponseEntity<SomeClass> result = restTemplate.getForEntity("/my/url", SomeClass.class);

        [...]
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 对于我的用例,我认为这是最好的方法,因为当HATEOS(特别是)发挥作用时,RestTemplate使响应的ORM映射更加直接. (2认同)