Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 540
idmitriev Avatar asked Dec 13 '17 09:12

idmitriev


People also ask

How do you test spring beans?

To test whether Spring MVC controllers are working as expected, use the @WebMvcTest annotation. To test that Spring WebFlux controllers are working as expected, you can use the @WebFluxTest annotation. You can use the @DataJpaTest annotation to test JPA applications.

What is @conditional annotation in spring?

Spring has introduced the @Conditional annotation that allows us to define custom conditions to apply to parts of our application context. Spring Boot builds on top of that and provides some pre-defined conditions so we don't have to implement them ourselves.

How do you use a spring conditional Bean?

Another way of making the component conditional would be to place the condition directly on the component class: @Service @Conditional(IsDevEnvCondition. class) class LoggingService { // ... } We can apply the above example to any bean declared with the @Component, @Service, @Repository, or @Controller annotations.

What is the use of ConditionalOnProperty?

In short, the @ConditionalOnProperty enables bean registration only if an environment property is present and has a specific value. By default, the specified property must be defined and not equal to false.


1 Answers

Assuming that you use SpringBoot 2 you might test like this:

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 "));
  }
}
like image 192
Kostyantyn Panchenko Avatar answered Sep 28 '22 18:09

Kostyantyn Panchenko