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,514評論 1 92
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網絡請求組件 FMDB本地數據庫組件 SD...
    陽明AGI閱讀 16,003評論 3 119
  • 看到這個問題,我想到我現在也是這樣的狀態,前段時間,因為工作沒有以前那樣上心了,遭到領導的點名批評,開始,我也沒有...
    舟舟style閱讀 215評論 0 3
  • 文/麥積夢境 下了一場雨在這個冬天 而北方早已是大雪覆蓋了 能想到漫天的雪花飄落起飛 路過山間路過村莊路過心間 你...
    麥積夢境閱讀 297評論 0 1