Issue
I use Spring, and created a test which loads the context using SpringRunner.
I have a bean which looks like this:
@Bean
public Properties kafkaStreamsProperties(){
final Properties props = new Properties();
props.put("A", "B");
props.put("C", "D");
return props;
}
I would like to extend it in my testing to also contain a property "E" --> "F".
I can easily do it in an inner @TestConfiguration class as follows:
public class test{
public static class MyConfig{
@Bean
public Properties kafkaStreamsProperties(){
final Properties props = new Properties();
props.put("A", "B");
props.put("C", "D");
props.put("E", "F");
return props;
}
}
}
But then when I change the production code, I'll have to "remember" changing the test too. Is there any way I can get the actual bean from the context and "replace" it with mine (using the actual one)?
Solution
In Spring Test you have @MockBean to mock a bean or @SpyBean
to Spy a bean:
Spring Boot includes a @MockBean annotation that can be used to define a Mockito mock for a bean inside your ApplicationContext. You can use the annotation to add new beans or replace a single existing bean definition.
Additionally, you can use @SpyBean to wrap any existing bean with a Mockito spy
Answered By - user7294900