java - 集成测试中 MockMvc 和 RestTemplate 的区别

标签 java spring spring-mvc junit integration-testing

两者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());

最佳答案

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

Spring MVC Test builds on the mock request and response from spring-test and does not require a running servlet container. The main difference is that actual Spring MVC configuration is loaded through the TestContext framework and that the request is performed by actually invoking the DispatcherServlet and all the same Spring MVC infrastructure that is used at runtime.

例如:

@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 Client-side 应用程序时应该使用:

If you have code using the RestTemplate, you’ll probably want to test it and to that you can target a running server or mock the RestTemplate. The client-side REST test support offers a third alternative, which is to use the actual RestTemplate but configure it with a custom ClientHttpRequestFactory that checks expectations against actual requests and returns stub responses.

示例:

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

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

// use RestTemplate ...

mockServer.verify();

另请阅读 this example

关于java - 集成测试中 MockMvc 和 RestTemplate 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25901985/

相关文章:

Java基于两个分隔符对字符串进行排序

java - 这个简单工厂是否违反了开闭原则?

java - 修改通用图像加载器

java - 为什么我的服务自动连接到代理?

java - Spring 和 HTTP 选项请求

java - Spring+Hibernate异常: No hibernate session bound to thread

java - 按第一个单词对 ArrayList 进行排序

java - Spring MVC 中的 HandlerInterceptor 和 HandlerInceptorAdaptor 有什么区别?

spring-mvc - 在 Zuul 代理后面时,Spring 重定向 url 问题

java - 了解Spring框架和MVC的流程