@SpringBootTest
- 目的是加载ApplicationContext,启动spring容器。
@RunWith
- 是一个测试启动器,可以加载SpringBoot测试注解
- 让测试在Spring容器环境下执行。如测试类中无此注解,将导致service,dao等自动注入失败
根据测试类中的代码是否涉及java项目中其他类,选择注释:
(1) 若测试类不涉及其他类中代码,@SpringBootTest即可满足执行要求
(2) 若测试类中使用方法,涉及到涉及其他类中代码,举例:spring线程池方法ThreadPoolTaskExecutor()涉及到项目中的配置类ThredPoolConfig,除了@SpringBootTest外必须添加@RunWith(SpringRunner.class)、@ContextConfiguration(classes = ""),从而设置上下文环境,读取配置类信息,否则测试执行失败。
测试类
@Test
public void testThreadPoolTaskExecutor(){
Runnable task = new Runnable() {
@Override
public void run() {
logger.debug("Hello testThreadPoolTaskExecutor");
}
};
for(int i = 0; i<10;i++){
taskExecutor.submit(task);
}
sleep(10000);
}
配置类
@Configuration
@EnableScheduling
@EnableAsync
public class ThreadPoolConfig {
}
仅使用@SpringBootTest注解时,报空指针异常
java.lang.NullPointerException
at com.nowcoder.community.ThreadPoolTest.testThreadPoolTaskExecutor(ThreadPoolTest.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59