springspring-bootspring-test

How to test Spring @Conditional beans


I have a @Conditional bean -

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

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

}

it can be either enabled or disabled. I want to create a test to cover both use cases. How can I do that? I just have one application.properties file:

user-controller.enabled=true

I can inject the property into bean and add a setter to manage it via code, but that solution is not elegant:

@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";
}

}

smth like this


Solution

  • It is not a perfect solution (as it will load two Spring Boot application contexts and this takes time) but you could create two test classes, each one testing a particular case by setting the properties of @TestPropertySource or @SpringBootTest

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

    or

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

    in the test class that tests the enabled case and

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

    or

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

    in the test class that tests the disabled case.


    A better solution would be probably to have a single class test.

    if you use Spring Boot 1, you could check EnvironmentTestUtils.addEnvironment.

    if you use Spring Boot 2, you could check TestPropertyValues.