Spring MVC 4.x.x Controller Junit单元测试

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();
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,584评论 1 92
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,012评论 3 119
  • 看到这个问题,我想到我现在也是这样的状态,前段时间,因为工作没有以前那样上心了,遭到领导的点名批评,开始,我也没有...
    舟舟style阅读 217评论 0 3
  • 文/麦积梦境 下了一场雨在这个冬天 而北方早已是大雪覆盖了 能想到漫天的雪花飘落起飞 路过山间路过村庄路过心间 你...
    麦积梦境阅读 302评论 0 1