使用春季启动在TestNg测试用例中提供BeanFactory Bean

时间:2018-11-01 05:34:09

标签: java spring spring-boot testng spring-test

我在弹簧靴中使用TestNg进行测试。 在我的测试用例中,对象之一具有BeanFactory Bean的依赖关系。

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

上面是测试用例,下面是Obj类

class Obj{

@Autowired
BeanFactory beanFactory;
//rest of the code

}

当我在测试用例上运行时,它给了我空指针异常,任何人都知道如何解决这个问题。

2 个答案:

答案 0 :(得分:1)

要注入/自动装配Spring上下文,您需要在Test Class中加载Spring上下文,例如with XML configurations

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

您还应该让Class扩展相关的类,例如AbstractTestNGSpringContextTests

  

抽象基础测试类,该类将Spring TestContext Framework与TestNG环境中的显式ApplicationContext测试支持集成在一起。

对于example

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

答案 1 :(得分:0)

我已经通过使用以下代码解决了问题,在@ContextConfiguration中添加了缺少的依赖项,并使用@SpringBootTest运行它

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