简体   繁体   中英

Provide BeanFactory Bean in TestNg test cases using spring boot

I am using TestNg in spring boot for test cases. One of the object in my test case have dependency of BeanFactory Bean.

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

above is the test case and below is the Obj class

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

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

Also you should Class should extends relevant class, as AbstractTestNGSpringContextTests

Abstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM