繁体   English   中英

如何测试 Spring @Conditional bean

[英]How to test Spring @Conditional beans

我有一个@Conditional bean -

@RestController("/user")
@ConditionalOnProperty(prefix = "user-controller", name = "enabled", havingValue = "true")
public void UserController {

@GetMapping
public String greetings() {
  return "Hello User";
}

}

它可以启用或禁用。 我想创建一个测试来涵盖这两个用例。 我怎样才能做到这一点? 我只有一个application.properties文件:

user-controller.enabled=true

我可以将属性注入 bean 并添加一个 setter 以通过代码对其进行管理,但该解决方案并不优雅:

@RestController("/user")
@ConditionalOnProperty(prefix = "user-controller", name = "enabled", havingValue = "true")
public void UserController {

@Value("${user-controller.enabled}")
private boolean enabled;

public void setEnabled(boolean enabled) {
 this.enabled = enabled;
}

@GetMapping
public String greetings() {
  return enabled ? "Hello User" : "Endpoint is disabled";
}

}

像这样

这不是一个完美的解决方案(因为它会加载两个 Spring Boot 应用程序上下文,这需要时间),但您可以创建两个测试类,每个测试类通过设置@TestPropertySource@SpringBootTest的属性来测试特定情况

@TestPropertySource(properties="user-controller.enabled=true")
public class UserControllerEnabledTest{...}

或者

@SpringBootTest(properties="user-controller.enabled=true")
public class UserControllerEnabledTest{...}

在测试启用案例的测试类中

@TestPropertySource(properties="user-controller.enabled=false")
public class UserControllerDisabledTest{...}

或者

@SpringBootTest(properties="user-controller.enabled=false")
public class UserControllerDisabledTest{...}

在测试禁用案例的测试类中。


更好的解决方案可能是进行单类测试。

如果你使用 Spring Boot 1,你可以检查EnvironmentTestUtils.addEnvironment

如果你使用 Spring Boot 2,你可以检查TestPropertyValues

假设您使用 SpringBoot 2,您可能会像这样进行测试:

public class UserControllerTest {

  private final ApplicationContextRunner runner = new ApplicationContextRunner()
      .withConfiguration(UserConfigurations.of(UserController.class));

  @Test
  public void testShouldBeDisabled() {
    runner.withPropertyValues("user-controller.enabled=false")
        .run(context -> assertThat(context).doesNotHaveBean("userController "));
  }
}

暂无
暂无

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

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