正如在此所说要测试应用程序的服务器端时,应使用RestTemplate:
Spring MVC Test建立在RestTemplate的模拟请求和响应的基础上,不需要运行中的servlet容器。 主要区别在于,实际的Spring MVC配置是通过TestContext框架加载的,而请求是通过实际调用29577116101163100100和运行时使用的所有相同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,当您要测试Rest Client-side应用程序时应使用:
如果您使用的代码是2957711610116316310016,则可能需要对其进行测试,并且可以针对正在运行的服务器或模拟RestTemplate。 客户端REST测试支持提供了第三种选择,即使用实际的RestTemplate,但使用自定义ClientHttpRequestFactory对其进行配置,该自定义的ClientHttpRequestFactory对照实际请求检查期望并返回存根响应。
例:
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("/greeting"))
.andRespond(withSuccess("Hello world", "text/plain"));
// use RestTemplate ...
mockServer.verify();
也读这个例子