如何通过unitTest中的每个测试覆盖属性

问题描述 投票:0回答:2

我的单元测试中有下一个配置:

@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@TestPropertySource(locations="classpath:itest.properties", properties = "server.username = inlined")

public class IqClientImplTest

通过我的测试类上的此配置,我将

server.username
属性从 .properties 文件中定义的属性更改为
inlined
但我需要在测试级别执行此操作,因为我需要重写此属性值每次测试都有不同的值,例如,一个测试可能为空,而另一个测试则需要管理值。

你知道如何在测试级别而不是类级别覆盖 .properties 值吗?

谢谢!

java junit spring-test
2个回答
0
投票

您可以在测试类中注入环境类。然后你可以尝试自定义环境属性。

例如: https://stackoverflow.com/a/35769953/1811348

在这里,您不会在构造后更改任何内容,而是在您想要覆盖设置的您自己的测试方法中更改。

要重置,您可以将 DirtiesContext 注释添加到测试方法中。

参考:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

另一种方法是在每个测试方法中设置系统属性:

System.setProperty("simple_test_env_property","somevalue");

还要确保添加肮脏的上下文。也许 dirtycontext 太过分了,不是必需的,但你可以结账。


0
投票

从 Spring Boot 2.5 开始,我基于 ReflectionTestUtils 类使用了一个非常简单的模式。

要记住的关键是确保测试在结束测试之前将正在突变的任何内容恢复到突变之前的相同状态。否则,这可能会成为很难追踪的错误来源。

  private static final String VENDOR_API_BAD_API_KEY = "ThIsIsNtAvAlIdApIkEy";

  @Test
  public void testVerifyPathwayBadApiKey() {
    //capture original value (injected as a property somewhere prior to this test context)
    //  to be restored to avoid impacting tests that follow
    var apiKeyValueOriginal = (String) ReflectionTestUtils.getField(this.vendorApi, "apiKey");
    try {
      ReflectionTestUtils.setField(this.vendorApi, "apiKey", VENDOR_API_BAD_API_KEY);

      //Code depending on the changed value in the vendorApiSy

    }
    finally {
      //reset to original value
      ReflectionTestUtils.setField(this.vendorApi, "apiKey", apiKeyValueOriginal);
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.