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