Spring MVC 4.x.x Controller Junit單元測試

MVC Controller中使用單元測試可以使開發(fā)過程簡化不少,調(diào)試也更為方便。
由于版本問題,可能導(dǎo)致官方文檔中的示例代碼并不能運行,所以在此寫一份工作中使用到的單元測試代碼,以備不時之需。

//去掉了大量的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();
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,943評論 1 92
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,614評論 19 139
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,211評論 3 119
  • 看到這個問題,我想到我現(xiàn)在也是這樣的狀態(tài),前段時間,因為工作沒有以前那樣上心了,遭到領(lǐng)導(dǎo)的點名批評,開始,我也沒有...
    舟舟style閱讀 249評論 0 3
  • 文/麥積夢境 下了一場雨在這個冬天 而北方早已是大雪覆蓋了 能想到漫天的雪花飄落起飛 路過山間路過村莊路過心間 你...
    麥積夢境閱讀 350評論 0 1

友情鏈接更多精彩內(nèi)容