簡體   English   中英

使用 spring boot 在 TestNg 測試用例中提供 BeanFactory Bean

[英]Provide BeanFactory Bean in TestNg test cases using spring boot

我在 Spring Boot 中使用 TestNg 作為測試用例。 我的測試用例中的一個對象依賴於 BeanFactory Bean。

@Test
void testMe(){
Obj obj = new Obj();
}

上面是測試用例,下面是 Obj 類

class Obj{

@Autowired
BeanFactory beanFactory;
//rest of the code

}

當我在測試用例上方運行時,它給了我空指針異常,任何人都知道如何解決這個問題。

要注入/自動裝配 Spring 上下文,您需要在測試類中加載 Spring 上下文,例如使用 XML 配置

@Test @ContextConfiguration(locations = { "classpath:spring-test-config.xml" })

您還應該 Class 擴展相關類,如AbstractTestNGSpringContextTests

抽象基礎測試類,它將 Spring TestContext Framework 與 TestNG 環境中的顯式 ApplicationContext 測試支持集成在一起。

例如

 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class SampleTestNGApplicationTests extends AbstractTestNGSpringContextTests {

我已經通過使用下面的代碼解決了,在@ContextConfiguration 中添加了缺少的依賴項,並使用@SpringBootTest 運行它

@SpringBootTest
@ContextConfiguration(classes = {ContextProvider.class, ApplicationContext.class, TraceAutoConfiguration.class})
public class DabekCostServiceTest extends AbstractTestNGSpringContextTests {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM