【问题标题】:Unable to load project environment variable in Spring Boot Unit Test无法在 Spring Boot 单元测试中加载项目环境变量
【发布时间】:2021-11-22 01:53:02
【问题描述】:

我在我的 Spring Boot 项目的 application-local.yml 中定义了一些变量,这些变量通过使用 @Value 注释在许多服务中使用。 现在,在尝试对这些服务进行单元测试时,该服务无法从 application-local.yml 检索变量的值,而是抛出 NullPointer 异常。 我该怎么办?

应用程序本地.yml:

variables:
    maxVal: 24

Service.java

@Value("${variables.maxVal:24}")
public Integer maxima;

FunctionA()
{
  return maxima+1;
}

单元测试

@Test
testFunctionA()
{
  assert.assertEquals(25,FunctionA())
}

【问题讨论】:

  • 你能分享你的测试吗,你可能缺少测试类的注释。
  • @RunWith(MockitoJUnitRunner.class) 公共类 testFunctionA {}

标签: java spring spring-boot unit-testing junit


【解决方案1】:

借助 @SpringBootTest 的 properties 属性,您可以通过这种简单的方式在 Spring Boot 的上下文中注入属性:

@SpringBootTest(properties="property.value=dummyValue")
public class FooTest{
    
   @Autowired
   Foo foo;
     
   @Test
   public void doThat(){
       ...
   }    
}

您可以使用 @TestPropertySource 作为替代,但它会添加一个额外的注释:

@SpringBootTest
@TestPropertySource(properties="property.value=dummyValue")
public class FooTest{ ...}

使用 Spring(不带 Spring Boot)应该会稍微复杂一些,但由于我很长时间没有在不带 Spring Boot 的情况下使用 Spring,所以我不想说一句愚蠢的话。

附带说明:如果要设置许多 @Value 字段,将它们提取到使用 @ConfigurationProperties 注释的类中更为相关,因为我们不希望构造函数具有太多参数。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    您的属性文件没有被加载。测试属性的正确方法是使用位于 test/resources 下的 application-test.yaml,它会在您运行测试时自动加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2018-01-16
      • 2015-03-16
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多