Spring提供了测试MVC的框架。
服务端测试(Server-Side Tests)
主要分为几个步骤:
需要注解@WebAppConfiguration
注入WebApplicationContext
MockMvc初始化
执行Request请求
定义期望值
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/webapp")
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class BaseControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
//初始化具体某个controller
// this.mockMvc = MockMvcBuilders.standaloneSetup(new CashierOrderController()).build();
}
@Test
public void testBase() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/")
.accept(MediaType.APPLICATION_JSON)
.param("foo", "bar"))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
客服端测试(Client-Side REST Tests)
目标是模拟一下响应response, 定义期望值
public class SampleTests {
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
@Before
public void setup() {
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.bindTo(this.restTemplate).ignoreExpectOrder().build();
}
@Test
public void performGet() throws Exception {
String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
@SuppressWarnings("unused")
Person ludwig = this.restTemplate.getForObject("/composers/{id}", Person.class, 42);
// We are only validating the request. The response is mocked out.
// hotel.getId() == 42
// hotel.getName().equals("Holiday Inn")
this.mockServer.verify();
}
}