java - @Value 属性在 JUnit 测试中始终为 null

标签 java spring-boot mockito junit5 spring-boot-test

我正在为可以使用两种不同配置运行的 Spring 应用程序编写一些单元测试。这两种不同的配置由两个 application.properties 文件给出。我需要为每个类编写两次测试,因为我需要验证适用于配置的更改不会影响另一个。

为此我在目录中创建了两个文件:

src/test/resources/application-configA.properties

src/test/resources/application-configB.properties

然后我尝试使用 @TestPropertySource 的两个不同值加载它们:

@SpringBootTest
@TestPropertySource(locations = "classpath:application-configA.properties")
class FooTest {
  @InjectMock
  Foo foo;

  @Mock
  ExternalDao dao;

  // perform test
}

Foo 类就是这个:

@Service
public class Foo {
  @Autowired
  private External dao;

  methodToTest() {
    Properties.getExampleProperty();
    this.dao.doSomething(); // this needs to be mocked!
  }
}

虽然 Properties 类是:

@Component
public class Properties {
  private static String example;

  @Value("${example:something}")
  public void setExampleProperty(String _example) {
    example = _example;
  }

  public static String getExampleProperty() {
    return example;
  }
}

问题是 Properties.getExampleProperty() 在测试期间总是返回 null,而在正常执行时它包含正确的值。

我试过:

  • 设置默认值(上面的“某物”)
  • application.properties 中设置一个值
  • 在/main 的 application-configA.properties 中设置一个值
  • 在/test 的 application-configA.properties 中设置一个值
  • 在@TestPropertySource 中设置内联值

这些都不起作用。

我读过 this question的答案,但看起来有些不同,它们对我没有帮助

最佳答案

经过多次尝试,终于找到了解决办法。该问题是由将 Spring 4 与 JUnit 5 一起使用引起的,即使它没有显示任何警告或错误,它也无法加载 Spring 上下文。老实说,我不知道 @SpringBootTest 在实践中做了什么。

解决方案是添加 spring-test-junit5 this answer 中所述的依赖性,然后执行以下步骤:

  • 移除@SpringBootTest注解
  • 添加@ExtendWith(SpringExtension.class),从spring-test-junit5导入类
  • 添加@Import(Properties.class)

现在测试的注释看起来像这样:

@ExtendWith(SpringExtension.class)
@PropertySource("classpath:application-configA.properties")
@TestPropertySource("classpath:application-configA.properties")
@Import(Properties.class)
class FooTest {

关于java - @Value 属性在 JUnit 测试中始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72459291/

相关文章:

java - 如何使用正则表达式包含“with Pattern.compile

Javassist 增强失败

java - Spring Data REST - 如何在投影中包含计算数据?

java - 使用 PowerMock 和 Mockito 模拟 Logger 和 LoggerFactory

java - 在Android中,何时在SurfaceView中创建的线程被销毁?

java - 在UNO安装中的Accumulo 2.0上运行Hello World示例InsertWithBatchWriter的问题

java - 用于生产的外部容器中的 Spring Boot 嵌入式容器或 war 文件

java - 改造 Https 调用给连接重置

mocking - 使用 Mockito 框架测试事件

java - 原因: no instance(s) of type variable(s) T exist so that void conforms to using mockito