java junit autowired_写Junit测试时用Autowired注入的类实例始终为空怎么解?
踩坑半天多,終于在網上尋覓到了解決方案,特此分享一下。
重要前提:src/main/java下的根包名必須和src/test/main的根包名完全一致,否則就會發生死活不能注入的情況,要繼續進行下面的步驟,請先確認這個重要前提。
再接下來就是常規配置了。
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不為空了,這說明注入正確了。
--2020-04-09--
參考資料二:《深入淺出SpringBoot2.x》楊開振著
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java junit autowired_写Junit测试时用Autowired注入的类实例始终为空怎么解?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对java面向对象的三大特征的理解_Ja
- 下一篇: java中类图概念,程序员眼中的UML(