Reputation: 61
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.
Upvotes: 1
Views: 952
Reputation: 61
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 {
Upvotes: 0
Reputation: 58774
To inject/autowire Spring context, you need to load Spring context in Test Class, e.g. 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 {
Upvotes: 1