参考自官网:Spring1.59的文档
一、测试 Testing
Springboot 测试支持由两个模块提供;
spring-boot-test 包含核心项目,而spring-boot-test-autoconfigure支持测试的自动配置。
大多数开发人员只使用spring-boot-starter-test就可以。它可以导入Spring Boot测试模块以及JUnit,AssertJ,Hamcrest和其他一些有用的库。
二、 测试范围依赖关系 Test scope dependencies
当你pom中引入了 spring-boot-starter-test
他将会自动引入下面的library库
如果这些并不能满足你,你可以自己附加测试依赖项。
三、测试springboot Testing Spring Boot applications
Spring Boot提供了一个@SpringBootTest注解,当您需要Spring Boot功能时,它可以用作标准spring-test @ContextConfiguration注释的替代方法。注解的工作原理是通过SpringApplication在测试中创建ApplicationContext。
所以Spring1.4以上的版本一般情况下是这样的:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootStarterTests {
在普通Spring项目中的测试一般情况下是这样的:
@RunWith(SpringRunner.class)
@ContextConfiguration(locations={"classpath:spring-servlet.xml", "classpath:spring-dao-test.xml", "classpath:spring-service-test.xml"})
public class MemberTest {
您可以使用@SpringBootTest的webEnvironment属性来进一步优化测试的运行方式:
- MOCK : 加载一个WebApplicationContext并提供一个模拟servlet环境。嵌入式servlet容器在使用此注释时不会启动。如果servlet API不在你的类路径上,这个模式将透明地回退到创建一个常规的非web应用程序上下文。可以与@AutoConfigureMockMvc结合使用,用于基于MockMvc的应用程序测试。
- RANDOM_PORT :
- DEFINED_PORT :
- NONE :
示例:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MemberTest {
注意:
1、如果你的测试是@Transactional,默认情况下它会在每个测试方法结束时回滚事务。 但是,由于使用RANDOM_PORT或DEFINED_PORT这种安排隐式地提供了一个真正的servlet环境,所以HTTP客户端和服务器将在不同的线程中运行,从而分离事务。 在这种情况下,在服务器上启动的任何事务都不会回滚。
2、除了@SpringBootTest之外,还提供了许多其他注释来测试应用程序的更具体的切片。 详情请参阅下文。
3、不要忘记还要在测试中添加@RunWith(SpringRunner.class),否则注释将被忽略。
四、检测测试配置
如果您熟悉Spring测试框架,则可以使用@ContextConfiguration(classes = ...)来指定要加载哪个Spring @Configuration。 或者,您可能经常在测试中使用嵌套的@Configuration类。
在测试Spring Boot应用程序时,这通常不是必需的。 Spring Boot的@ *测试注解将自动搜索您的主要配置,只要您没有明确定义一个。
搜索算法从包含测试的包开始工作,直到找到@SpringBootApplication或@SpringBootConfiguration注解。 只要你以合理的方式构建你的代码,你的主要配置通常是可以找到的。
五、使用随机端口 Working with random ports
如果您需要启动完整的运行服务器进行测试,我们建议您使用随机端口。 如果您使用@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT),则每次运行测试时都会随机选取一个可用端口。
@LocalServerPort注解可以用来注入用于测试的实际端口。 为了方便起见,需要对已启动的服务器进行REST调用的测试还可以@Autowire一个TestRestTemplate,它将解析到正在运行的服务器的相关链接。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortExampleTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
}
}
后面还有一些测试Springmvc url , json 序列化的。由于目前没用到就不继续写了。改天来填坑