加载测试

记载测试临时属性和配置应用于小范围测试环境

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
//如果config测试类没有加@Configuration就需要@import(config测试类.class)
//@Import(MsgConfig.class)
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.NONE 不启动web测试服务
*SpringBootTest.WebEnvironment.DEFINED_PORT 以你定义的端口启动web测试服务,没有就默认以端口启动
*SpringBootTest.WebEnvironment.RANDOM.PORT 随机端口启动web测试服务
*/
@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)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {

@Test
//注入虚拟MVC调用对象
void webTest(@Autowired MockMvc mvc) throws Exception {
//创建虚拟请求
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
//执行对应的请求
mvc.perform(builder);
}
}