SpringBoot单元测试
程序员文章站
2022-04-26 09:22:21
...
目录
3 使用 SpringBoot 整合 Junit 做单元测试
1 pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加 junit 环境的 jar 包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
2 编写业务代码
2.1 Dao层
@Repository
public class UserDaoImpl {
public void saveUser(){
System.out.println("insert into users.....");
}
}
2.2业务层
@Service
public class UserServiceImpl {
@Autowired
private UserDaoImpl userDaoImpl;
public void addUser(){
this.userDaoImpl.saveUser();
}
}
2.3编写启动类
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
3 使用 SpringBoot 整合 Junit 做单元测试
@RunWith:启动器 SpringJUnit4ClassRunner.class: 让 junit 与 spring 环境进行整合
@SpringBootTest(classes={App.class})
1,当前类为 springBoot 的测试类
2,加载 SpringBoot 启动类。 启动springBoot
junit 与 spring 整合
@Contextconfiguartion("classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})
public class UserServiceTest {
@Autowired
private UserServiceImpl userServiceImpl;
@Test
public void testAddUser(){
this.userServiceImpl.addUser();
}
}