How to limit visibility of a @Factory in test #10129
-
In one of my tests I would like to replace a bean with a different (mock) implementation, so that I would end up with this configuration:
MyController is using a bean implementing ValidationStrategy interface, like so: @Controller
public class MyController {
private final ValidationStrategy validator;
public MyController(@Named("validationStrategyNoOp") ValidationStrategy validationStrategy) { //initializations
}
//other stuff
} ValidationStrategy has a default implementation, ValidationStrategyImpl: @Singleton
public class ValidationStrategyImpl { //the impl omitted for brevity
} AND a NO-OP implementation ValidationStrategyNoOp that is temporarily referenced in the controller via the Named annotation. Now, in the MyControllerRegularTest test I can see that the implementation ValidationStrategyNoOp is injected in the MyController as expected. For the MyControllerCornerCaseTest test I need a different implementation of ValidationStrategy, so I thought I would solve the problem by providing a bean factory in the test, like this: @MicronautTest
public class MyControllerCornerCaseTest {
/* actual tests omitted */
@Factory
static class StrategyProvider {
@Bean @Replaces(ValidationStrategyNoOp.class) @Named("validationStrategyNoOp")
public ValidationStrategy specialCaseStrategy() {
return new ValidationStrategy() {
//some mock implementation useful ONLY for this test!
}
}
}
} If I run ONLY MyControllerCornerCaseTest, the tests pass (I see this mock implementation being injected by the factory). BUT the problem is that now the MyControllerRegularTest sees too this bean factory and it won't inject anymore the ValidationStrategyNoOp , but the one provided by the MyControllerCornerCaseTest.StrategyProvider factory! So the question is, is there another and better way of specifying an interface implementation, with limited visibility in just one(or a few) test(s)? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is what |
Beta Was this translation helpful? Give feedback.
This is what
@MockBean(ValidationStrategyNoOp.class)
is for. It isolates the bean to only the test