Spring整合junit:
1.导入(spring-test和junit)jar的maven坐标(junit使用版本1.12及以上)
2.使用spring的Runwith注解替换SpringJUnit4ClassRunner类(junit整合了main方法)
3.导入spring的配置文件
spring配置test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@RunWith :用来代替SpringJUnit4ClassRunner类,让spring管理test方法
@ContextConfiguration: 用来引入配置文件
springboot和spring类似
pom.xml和java注解
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
@RunWith(SpringRunner.class)
@SpringBootTest(classes = XXXApplication.class)
@WebAppConfiguration
XXXApplication.class:是指springboot的启动类(不写这个会导致无法注入)
@RunWith :用来代替SpringJUnit4ClassRunner类,让spring管理test方法
@SpringBootTest : 让springboot找到启动项
@WebAppConfiguration : 表示扫描配置问题,默认就是springboot的配置
类命名方式 测试类+Test; 方法命名方式 test+方法名;
报错1
没有设置JUnit4
改成JUnit4
报错2 maven install时,找不到测试类
将maven插件中改成<skip>true</skip>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>