Java 集成测试中 MockMvc 和 RestTemplate 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25901985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between MockMvc and RestTemplate in integration tests
提问by Denis C de Azevedo
Both MockMvcand RestTemplateare used for integration tests with Spring and JUnit.
无论MockMvc和RestTemplate用于与Spring和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());
采纳答案by nivash
As said in thisarticle you should use MockMvc
when you want to test Server-sideof application:
正如在说这个文章你应该使用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.
Spring MVC 测试建立在模拟请求和响应的基础上,
spring-test
不需要正在运行的 servlet 容器。主要区别在于实际的 Spring MVC 配置是通过 TestContext 框架加载的,并且请求是通过实际调用DispatcherServlet
在运行时使用的所有相同的 Spring MVC 基础结构来执行的。
for example:
例如:
@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"));
}}
And RestTemplate
you should use when you want to test Rest Client-sideapplication:
RestTemplate
当您想测试Rest 客户端应用程序时,您应该使用:
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。客户端 REST 测试支持提供了第三种选择,即使用实际RestTemplate
但使用自定义ClientHttpRequestFactory
来配置它,以根据实际请求检查预期并返回存根响应。
example:
例子:
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("/greeting"))
.andRespond(withSuccess("Hello world", "text/plain"));
// use RestTemplate ...
mockServer.verify();
also read this example
也阅读这个例子
回答by Sotirios Delimanolis
With MockMvc
, you're typically setting up a whole web application context and mocking the HTTP requests and responses. So, although a fake DispatcherServlet
is up and running, simulating how your MVC stack will function, there are no real network connections made.
使用MockMvc
,您通常会设置整个 Web 应用程序上下文并模拟 HTTP 请求和响应。因此,虽然一个假的DispatcherServlet
已经启动并运行,模拟您的 MVC 堆栈将如何运作,但没有建立真正的网络连接。
With RestTemplate
, you have to deploy an actual server instance to listen for the HTTP requests you send.
使用RestTemplate
,您必须部署一个实际的服务器实例来侦听您发送的 HTTP 请求。
回答by Michael B?ckling
It is possible to use both RestTemplate and MockMvc!
可以同时使用 RestTemplate 和 MockMvc!
This is useful if you have a separate client where you already do the tedious mapping of Java objects to URLs and converting to and from Json, and you want to reuse that for your MockMVC tests.
如果您有一个单独的客户端,您已经在其中执行了 Java 对象到 URL 的繁琐映射以及与 Json 之间的转换,并且您希望将其重用于 MockMVC 测试,那么这将非常有用。
Here is how to do it:
这是如何做到的:
@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);
[...]
}
}