SpringBoot整合Junit步骤:
1、快速搭建SpringBoot工程
SpringBoot工程创建成功后,删除一些无用的文件后的目录结构如下:
2、以上的SpringBoot工程创建完成之后,在工程的pom文件中会自动导入Junit 的starter-test的起步依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--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>
</dependencies>
3、编写测试类
package com.example;
import org.springframework.stereotype.Service;
@Service
public class ServiceImpl {
public void add(){
System.out.println("ServiceImpl ...");
}
}
4、添加测试相关的注解
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootTestApplication.class) //classes = 启动类.class
5、编写测试方法,对业务层的类进行测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootTestApplication.class) //classes = 启动类.class
class SpringbootTestApplicationTests {
@Autowired
private ServiceImpl serviceImpl; //通过注解注入被测试的类
@Test //测试方法注解
public void testAdd() {
serviceImpl.add(); //被测试的方法
}
}
6、执行测试方法
测试效果如下,业务层中被测试类的方法中的输出执行成功
总结注意:
a、如果test.java下的测试类所在的包与被测试类的包名一致的话,@SpringBootTest括号中的内容可以不写
@SpringBootTest(classes = SpringbootTestApplication.class) //classes = 启动类.class
可以写成
@SpringBootTest