Junit 模擬http請求快速上手

junit相信做java的都不陌生,用過的人也很多。本人一直沒寫過junit的http測試,最近有用到,網上的資料不少,但是比較雜。所以整理一個讓你快速開始寫代碼的文章。本文屬於快速入門使用,不屬於深入研究類型。

本文是基於springboot,junit4

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RouterApplication.class) // 這個是你的springboot啓動類
@ActiveProfiles("junit") // 這個是你使用的配置文件profile。一般都會使用多套配置文件,和開發,生產的配置區分開
public class Tests {

    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc對象
    }

    @Test
    public void testMockMvc() throws Exception{
       //post請求
        MockHttpServletRequestBuilder post = MockMvcRequestBuilders.post("/deliver"); //  接口路徑
        post.content(reqStrDemo.getBytes("UTF-8"));

        String string = mockMvc.perform(post).andReturn().getResponse().getContentAsString();
        System.out.println(string);
    }
}

或者還有一種寫法。本人使用的是下面這種方法。兩種方式都自測過,都可以。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RouterApplication.class) // 這個是你的springboot啓動類
@ActiveProfiles("junit") // 這個是你使用的配置文件profile。一般都會使用多套配置文件,和開發,生產的配置區分開
public class Tests {

    @Autowired
    protected TestController controller; // 把要測試的controller注入進來

    @Test
    public void test() throws Exception{
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setContent(xxxxxxx); // 直接設置請求內容(post),參數等也在request裏設置
        MockHttpServletResponse response = new MockHttpServletResponse();

		controller.testMethod(request, response)
        String string = response.getContentAsString();
        System.out.println(string);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章