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
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.
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.
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.
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.
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 "));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With