需求:
SpringBoot整合Junit。
实现步骤:
①搭建SpringBoot工程
②引入starter-test起步依赖
③编写测试类
④添加测试相关注解
@RunWith(SpringRunner.class)@SpringBootTest(classes =启动类class)
⑤编写测试方法
具体实现
项目结构

1、使用idea的spring initialer创建web工程,自动引入start-test依赖和创建SpringBootTest类
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://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.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.devtao.study</groupId>
<artifactId>springboot-junit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-junit</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
SpringbootJunitApplication.java
package com.devtao.study.springbootjunit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootJunitApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootJunitApplication.class, args);
}
}
PersonService.java
package com.devtao.study.service;
import org.springframework.stereotype.Service;
/**
* @program: springboot-junit
* @description:
* @author: Liu Tao
* @create: 2021-10-27 09:58
**/
public interface PersonService {
public void add();
}
PersonServiceImpl.java
package com.devtao.study.service.impl;
import com.devtao.study.service.PersonService;
import org.springframework.stereotype.Service;
/**
* @program: springboot-junit
* @description:
* @author: Liu Tao
* @create: 2021-10-27 09:58
**/
@Service("personService")
public class PersonServiceImpl implements PersonService {
@Override
public void add() {
System.out.println("add new record");
}
}