Overriding an Autowired Bean in Unit Tests Overriding an Autowired Bean in Unit Tests spring spring

Overriding an Autowired Bean in Unit Tests


If you just simply want to provide a different bean in your tests, i think you don't need to use spring profiles or mockito.

Just do the following:

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = { TestConfig.class })public class MyTest{    @Configuration    @Import(Application.class) // the actual configuration    public static class TestConfig    {        @Bean        public IMyService myService()        {            return new MockedMyService();        }    }    @Test    public void test()    {        ....    }}

NOTE: tested with spring boot 1.3.2 / spring 4.2.4


In Spring Boot 1.4 there's a simple way for doing that:

@RunWith(SpringRunner.class)@SpringBootTest(classes = { MyApplication.class })public class MyTests {    @MockBean    private MyBeanClass myTestBean;    @Before    public void setup() {         ...         when(myTestBean.doSomething()).thenReturn(someResult);    }    @Test    public void test() {         // MyBeanClass bean is replaced with myTestBean in the ApplicationContext here    }}


I had similar problem and I solved with a mix and I find this one more useful and reusable. I created a spring profile for the tests and a config class that overrides the beans I want to mock in a very simple way:

@Profile("test")@Configuration@Import(ApplicationConfiguration.class)public class ConfigurationTests {    @MockBean    private Producer kafkaProducer;    @MockBean    private SlackNotifier slackNotifier;}

By doing that I can @Autowire those mock beans and use mockito to verify on them. Main advantage is that now all tests seamlessly get the mock beans without any per-test change. Tested with:

spring boot 1.4.2