java - 如何使用 ConditionalOnProperty 禁用 junit 测试?

我使用环境变量作为功能标志来调节我的服务中的一些端点。对于一个控制器,我将 @ConditionalOnProperty("enable.v2.foo") 放在类级别,对于另一个控制器,我将 @ConditionalOnProperty("enable.v2.ba.endpoint2") 放在特定方法上。现在我有一些端到端的 junit 4 测试调用这些端点。签名是

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TaxServiceApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class E2ETest432 {
...

所以我想如果整个类测试我想要切换的端点,我可以将 @ConditionalOnProperty("enable.v2.ba.endpoint2") 放在方法级别和类级别的特定测试上。

但是如果我运行所有测试,那么这些测试也会运行。我什至验证了它们已被阅读并具有正确的 value:

@Value("${enable.v2.ba.endpoint2}")
  private boolean switchAsBoolean;


  @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:dataset/....sql")
  @Sql(executionPhase = ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:dataset/....sql")
  @Test
  @ConditionalOnProperty("enable.v2.ba.endpoint2")
  public void shouldReturnDeliveryCostsForVehicle() throws IOException {
      Assertions.assertThat(switchAsBoolean).isFalse();
      ...
  }

此测试失败是因为端点不存在(-> 状态代码意外地为 404),而不是因为 value 为假!

如何在相同的功能标志上调整我的测试?

回答1

您可以在测试中添加 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html 注释来设置属性 value。例如

@TestPropertySource(properties = "enable.v2.ba.endpoint2 = true")

您必须有 2 个测试类,一个注释为 true,另一个注释为 false。

相似文章

随机推荐

最新文章