- pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 位置
如果测试类仅是代码测试,而不引入的service mapper bean,位置随意就行
- 找到启动类
- 看启动类代码中所在package,如:package com.ruoyi;
- 在项目中与src/main同级目录下建立一个test,一般idea会给出test文件名提示
- 然后总的路径就是 src/test/java + 启动类代码中所在package
- 可以在这个路径中随意建立包,只是必须属于这个路径中
- 代码举例
package com.ruoyi.abcd;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class MainTest {
@Autowired
private ISysConfigService configService;
@Test
public void test01() {
System.out.println("32432423");
List<SysConfig> list = configService.selectConfigList(new SysConfig());
System.out.println(list);
}
}
以上案例代码是junit5的版本,spring-boot-starter-test默认使用JUnit 5(从Spring Boot 2.2.0开始),但你可以通过配置来覆盖它以使用JUnit 4。
一般情况下不做更改,有很多方法将JUnit 5改成JUnit 4。从spring-boot-starter-test中排出JUnit 5,另外加JUnit 4依赖,其实这样做没必要,直接加JUnit 4依赖就行,这样项目中就既能用JUnit 5也能用JUnit 4。
junit 4代码举例:
package com.ruoyi.abcd;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
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.test.context.junit4.SpringRunner;
import java.util.List;
@SpringBootTest
@RunWith(SpringRunner.class)
public class JUnit4Test {
@Autowired
private ISysConfigService configService;
@Test
public void test01() {
System.out.println("32432423");
List<SysConfig> list = configService.selectConfigList(new SysConfig());
System.out.println(list);
}
}
拓展
我们写的测试类,不局限与模块的限制,在所有模块都能写,类路径也要写启动类同级或以下。有一点细节,就是如果在多个模块写测试类,每个模块都要引入相同依赖,可以在父级模块的标签中直接引入,这样就不用都引入了。注意一下父级pom中依赖的位置,是直接在标签中还是在标签中的中,如果是后者则需要再需要写测试类的模块中再引入一次,只是不写版本号。