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

Cri*_*ìna 7 java mockito spring-boot 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
}
Run Code Online (Sandbox Code Playgroud)

该类Foo是这样的:

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

  methodToTest() {
    Properties.getExampleProperty();
    this.dao.doSomething(); // this needs to be mocked!
  }
}
Run Code Online (Sandbox Code Playgroud)

虽然班级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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我试过了:

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

这些都不起作用。

我已经阅读了这个问题的答案,但看起来有些不同,它们对我没有帮助

Cri*_*ìna 4

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

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

  • 删除@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 {
Run Code Online (Sandbox Code Playgroud)