如何测试Spring @Conditional Bean

idm*_*iev 2 spring spring-test spring-boot

我有一个@Conditional bean-

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

user-controller.enabled=true
Run Code Online (Sandbox Code Playgroud)

我可以将属性注入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";
}

}
Run Code Online (Sandbox Code Playgroud)

像这样

小智 9

假设您使用 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 "));
  }
}
Run Code Online (Sandbox Code Playgroud)


dav*_*xxx 5

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

@TestPropertySource(properties="user-controller.enabled=true")
public class UserControllerEnabledTest{...}
Run Code Online (Sandbox Code Playgroud)

要么

@SpringBootTest(properties="user-controller.enabled=true")
public class UserControllerEnabledTest{...}
Run Code Online (Sandbox Code Playgroud)

在测试已启用案例的测试类中,以及

@TestPropertySource(properties="user-controller.enabled=false")
public class UserControllerDisabledTest{...}
Run Code Online (Sandbox Code Playgroud)

要么

@SpringBootTest(properties="user-controller.enabled=false")
public class UserControllerDisabledTest{...}
Run Code Online (Sandbox Code Playgroud)

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


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

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

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