1、spring中,普通接口的单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test.xml")
public class TestClass {
@Autowired
private ApplicationContext context;
@Before
public void before() {
}
@Test
public void test() {
context.getBean("helloWorld", HelloWorld.class);
}
}
2、spring中,rest接口的单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@springJunitWebConfig(locations = "classpath:test.xml")
public class TestClass {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void before() {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void test() throws Exception {
// mock一个request
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("http://192.168.0.201:8081/hello")
.contentType(MediaType.APPLICATION_JSON_UTF8);
// 使用moc的mvc執行mock的request
ResultActions result = mvc.perform(request);
// 进行结果判断
result.andExpect(MockMvcResultMatchers.status().is(200)).andExpect(MockMvcResultMatchers.content()
.string("hello world(host : X4KX5720JF4PELK,port : -1,serviceId : hello-service)"));
}
}
3、springboot中,rest接口的单元测试
@RunWith(SpringJUnit4ClassRunner.class)
// 这里的class后面是Application引导类,因为在Application上配置了@componentScan
@SpringBootTest(classes = Application.class)
public class TestClass {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void before() {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void test() throws Exception {
// mock一个request
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("http://192.168.0.201:8081/hello")
.contentType(MediaType.APPLICATION_JSON_UTF8);
// 使用moc的mvc執行mock的request
ResultActions result = mvc.perform(request);
// 进行结果判断
result.andExpect(MockMvcResultMatchers.status().is(200)).andExpect(MockMvcResultMatchers.content()
.string("hello world(host : X4KX5720JF4PELK,port : -1,serviceId : hello-service)"));
}
}
4、批量执行测试用例:只需要执行一次context的加载
@RunWith(Suite.class)
@SuiteClasses({ TestClass.class, HelloWorld1ApplicationTests.class })
public class SuiteTestClass {
}
5、总结
(1)注释总结
单元测试时使用到的注释有:@RunWith、@ContextConfiguration、@SpringJunitWebConfig、
@SpringBootTest、@SuiteClasses
@RunWith :指定以什么方式启动测试类,启动方式有SpringRuner(SpringBoot测试类的启动方
式)、SpringJUnit4ClassRunner(Spring测试类的启动方式)、Suite(批量测试类的启动方式)
@ContextConfiguration :指定上下文的配置文件位置,加载上下文,上下文是 ApplicationContext
@springJunitWebConfig:指定上下文的配置文件位置,加载上下文,上下文是WebApplicationContext
@SpringBootTest:不需要指定配置上下文的配置文件位置,加载上下文,上下文是WebApplicationContext
@SuiteClasses:指定批量测试的测试类
(2)restful请求的模拟测试工具
MockMvcRequestBuilders:rest请求测试的模拟工具
MockMvcResultMatchers:rest请求响应结果的检查工具