两者MockMvc和 RestTemplate用于与 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 theDispatcherServlet
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 actualRestTemplate
but configure it with a customClientHttpRequestFactory
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/