如何测试 Spring @Conditional beans

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 启动应用程序上下文,这需要时间)但是你可以创建两个测试 classes,每个测试一个特定的案例设置 @TestPropertySource@SpringBootTest

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

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

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

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

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

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


更好的解决方案可能是进行一次 class 测试。

如果你使用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 "));
  }
}