java junit autowired_写Junit测试时用Autowired注入的类实例始终为空怎么解?

当在写JUnit测试时遇到使用Autowired注解的类实例为空的问题,关键在于确保src/main/java和src/test/java的根包名一致。添加spring-boot-starter-test依赖,为需要注入的类添加Component或Service注解,并使用SpringRunner和@SpringBootTest注解写测试类,这样才能正确注入并运行测试。
摘要由CSDN通过智能技术生成

踩坑半天多,终于在网上寻觅到了解决方案,特此分享一下。

重要前提:src/main/java下的根包名必须和src/test/main的根包名完全一致,否则就会发生死活不能注入的情况,要继续进行下面的步骤,请先确认这个重要前提。

6e13737b1088df663a85b0fd2588a900.png

再接下来就是常规配置了。

pom.xml增加依赖spring-boot-starter-test,它会引入JUnit的测试包:

org.springframework.boot

spring-boot-starter-test

test

然后给需要注入的类增加Component或是Service注解:

@SpringBootApplication

@Componentpublic class WebhookApplication implementsCommandLineRunner {private final Logger logger = LoggerFactory.getLogger(WebhookApplication.class);//Proxy server(from application-dev(stg,prod,qa).yml)

@Value("${webhook.proxy}")privateString proxy;public voidsetProxy(String proxy) {this.proxy =proxy;

}

...

}

@Servicepublic classWebhookService {private final Logger logger = LoggerFactory.getLogger(WebhookService.class);

...

}

写Component或是Service注解目的是能让这些类可以被Autowired方式输入。

再往下就是写测试类了:

@RunWith(SpringRunner.class)

@SpringBootTestpublic classWebhookApplicationTest {

@Autowiredprivate WebhookApplication app=null;

@Autowiredprivate WebhookService service=null;

@Testpublic voidtest() {

Assert.assertNotNull(app);

}

@Testpublic voidtest2() {

Assert.assertNotNull(service);

}

...

}

其中SpringRunner是Spring结合JUnit的运行器,说明这里可以进行JUnit测试。

注解@SpringBootTest是可以配置SpringBoot的关于测试的相关功能。

完事以后,运行test或是test2,能发现app或是service不为空了,这说明注入正确了。

cf5c3a40e3f53eff2e40d6b777d8a885.png

97e0592b6c288dced2b6cc8f80ce960a.png

--2020-04-09--

参考资料二:《深入浅出SpringBoot2.x》杨开振著

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值