MVC Controller中使用单元测试可以使开发过程简化不少,调试也更为方便。
由于版本问题,可能导致官方文档中的示例代码并不能运行,所以在此写一份工作中使用到的单元测试代码,以备不时之需。
//去掉了大量的import语句
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-mvc.xml")
@TestPropertySource(locations = "classpath:config-test.properties")
public class CashierControllerTest {
@Autowired
@Qualifier("webApplicationContext")
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testWxJsTicket() throws Exception {
MvcResult result = this.mockMvc.perform(get("/api/pay/wxJsTokens?appid=6000")
.accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE)))
.andExpect(status().isOk())
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
@Test
public void testUnifiedOrder() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("version", "v1.0");
map.put("orderId", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime()));
map.put("orderAmount", "0.01");
map.put("orderTime", new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime()));
map.put("productName", "测试商品");
UriComponentsBuilder builder = UriComponentsBuilder
.fromPath("/api/pay/sign");
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
System.out.println(builder.toUriString());
MvcResult result = this.mockMvc.perform(get(builder.toUriString())
.accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.sign").exists())
.andReturn();
map.put("sign", JsonPath.read(
result.getResponse().getContentAsString(),
"$.data.sign"
));
UriComponentsBuilder orderBuilder = UriComponentsBuilder
.fromPath("/api/pay/cashierOrder");
System.out.println(new ObjectMapper().writeValueAsString(map));
}
}
完整示例,可用来继承
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-mvc.xml")
public class ControllerBaseTest {
@Autowired
@Qualifier("webApplicationContext")
private WebApplicationContext wac;
protected MockMvc mockMvc;
@BeforeClass
public static void setSystemProperty() {
Properties properties = System.getProperties();
properties.setProperty("spring.profiles.active", "test");
}
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
}