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請求響應結果的檢查工具