简体   繁体   English

使用 spring boot 在 TestNg 测试用例中提供 BeanFactory Bean

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

I am using TestNg in spring boot for test cases.我在 Spring Boot 中使用 TestNg 作为测试用例。 One of the object in my test case have dependency of BeanFactory Bean.我的测试用例中的一个对象依赖于 BeanFactory Bean。

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

above is the test case and below is the Obj class上面是测试用例,下面是 Obj 类

class Obj{

@Autowired
BeanFactory beanFactory;
//rest of the code

}

when I run above test case it gives me null pointer exception , anybody has idea how to solve this.当我在测试用例上方运行时,它给了我空指针异常,任何人都知道如何解决这个问题。

To inject/autowire Spring context, you need to load Spring context in Test Class, eg with XML configurations要注入/自动装配 Spring 上下文,您需要在测试类中加载 Spring 上下文,例如使用 XML 配置

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

Also you should Class should extends relevant class, as AbstractTestNGSpringContextTests您还应该 Class 扩展相关类,如AbstractTestNGSpringContextTests

Abstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment.抽象基础测试类,它将 Spring TestContext Framework 与 TestNG 环境中的显式 ApplicationContext 测试支持集成在一起。

For example : 例如

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

I have solved by using below code , adding missing dependency in @ContextConfiguration , and running it with @SpringBootTest我已经通过使用下面的代码解决了,在@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