【问题标题】:Provide BeanFactory Bean in TestNg test cases using spring boot使用 Spring Boot 在 TestNg 测试用例中提供 BeanFactory Bean
【发布时间】:2018-11-01 05:34:09
【问题描述】:

我在 Spring Boot 中使用 TestNg 来测试用例。 我的测试用例中的一个对象具有 BeanFactory Bean 的依赖关系。

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

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

class Obj{

@Autowired
BeanFactory beanFactory;
//rest of the code

}

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

【问题讨论】:

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


【解决方案1】:

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

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

你也应该类应该扩展相关的类,如AbstractTestNGSpringContextTests

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

对于example

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

【讨论】:

  • @ContextConfiguration(locations = { "classpath:spring-test-config.xml" }) public class DabekCostServiceTest extends AbstractTestNGSpringContextTests { 我尝试了您的解决方案,但出现以下错误 原因:java.io.FileNotFoundException:无法打开类路径资源 [spring-test-config.xml],因为它不存在
  • @Aviral 这是一个示例,请使用 Spring 的配置方式编辑您的问题,测试应使用相应的配置
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多