正如在说这个 文章你应该使用
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")); }}而且
RestTemplate你应该使用当你想测试 休息客户端 应用程序:
如果您使用编写代码
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();也读这个例子



