繁体   English   中英

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

[英]@Value properties are always null in JUnit 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 中设置内联值

这些都不起作用。

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

经过多次尝试,我终于找到了解决方案。 该问题是由使用 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 {

我建议使用@Before来设置单元测试中的值,如果它是使用org.springframework.test.util.ReflectionTestUtils的整个类,

但是,为了这样做,您必须在测试类中注入Properties实例

@InjectMocks Properties properties;
...
@Before
  public void setUp() {
    ReflectionTestUtils.setField(properties, "example", "something");
  }

或者,您也可以在@Test中使用相同的ReflectionTestUtil - 我认为

更新:您使用@TestPropertySource的方式绝对正确,但使用术语locationproperties可能存在一些冲突,在我看来,我已经看到代码在做,

@TestPropertySource(properties = "classpath:application-configA.properties")

另外,您是否尝试过添加@ActiveProfile('test')@AutoConfigureMockMvc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM