加载测试
记载测试临时属性和配置应用于小范围测试环境
1.加载测试专用属性
在启动测试环境的时候可以通过properties参数设置环境专用的属性
1 2 3 4 5 6 7 8 9 10 11 12
| @SpringBootTest(properties = {"test.prop=test1"},args={"--test.prop=test2"}) public class PropertiesTest {
@Value("${test.prop}") private String msg;
@Test void testProp(){ System.out.println(msg); }
}
|
2.加载测试专用配置
使用@Import注解加载当前测试类专用的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Configuration public class MsgConfig { @Bean public String msg(){ return "I is Bean"; } }
@SpringBootTest
public class ConfigTest {
@Autowired private String msg;
@Test void msgTest(){ System.out.println(msg); }
}
|
3.测试环境中启动web环境
模拟端口
1 2 3 4 5 6 7 8 9 10 11 12 13
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class WebTest {
@Test void test(){ } }
|
发送虚拟请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc public class WebTest {
@Test void webTest(@Autowired MockMvc mvc) throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books"); mvc.perform(builder); } }
|