Junit测试SpringBoot中
前言
Github:https://github.com/HealerJean
1、sprinboot中直接写测试用例
1.1、如果直接输入@Test
就会自动让我将这个版本放到pom中去
1.1.1、然后pom.xml
中就出现了下面的
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
1.1.2、如果运行报下面错误
主要是上面的依赖导致的错误
Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
at org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry.loadTestEngines(ServiceLoaderTestEngineRegistry.java:30)
at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.createListeners(JUnit5IdeaTestRunner.java:39)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
1.2、使用新的依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2、SpringBoot真正测试
2.1、maven
<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>
2.2、开始测试
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppApplication.class)
public class MainTest {
@Autowired
private CacheService cacheService ;
@Test
public void test(){
while (true){
boolean lock = cacheService.lock("TEST", 1, TimeUnit.MINUTES);
if (lock){
log.info("锁状态【{}】", lock);
}
}
}
}
3、单元测试可以暂停、继续(通过键盘控制)
3.1、idea配置(记得重启idea)
加上: -Deditable.java.test.console=true
3.2、测试
@Slf4j
@SpringBootTest(classes = StartApp.class)
@RunWith(SpringRunner.class)
public class BatteryInfoTest {
@Autowired
private CacheService cacheService ;
@Test
public void testSelect() {
before();
boolean lock = cacheService.lock("TEST", 1, TimeUnit.MINUTES);
if (lock){
log.info("锁状态【{}】", lock);
}
//继续调用
testSelect();
}
public void before(){
Scanner scanner = new Scanner(System.in);
System.out.println("=========请输入任意内容即可继续=======================");
scanner.nextLine();
}
}