Spring测试类中@SpringBootTest、@RunWith(SpringRunner.class)、@ContextConfiguration(classes = ““)的使用

文章讨论了在SpringBoot测试中,@SpringBootTest注解用于加载ApplicationContext,启动Spring容器。而@RunWith(SpringRunner.class)与@ContextConfiguration是确保涉及其他类的测试能在正确上下文中执行的关键,例如在测试线程池配置时。当缺少这些注解时,可能会导致如空指针异常等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值