javaspringspring-bootspring-boot-test

How to replace a @MockBean?


Is it possible to replace an inherited @MockBean with the real @Bean?

I have an abstract class that defines many configurations and a setup for all ITests. Only for one single test I want to make use of the real bean, and not used the mocked one. But still inherit the rest of the configuration.

@Service
public class WrapperService {
       @Autowired
       private SomeService some;
}

@RunWith(SpringRunner.class)
@SpringBootTest(...)
public abstract class AbstractITest {
    //many more complex configurations

    @MockBean
    private SomeService service;
}

public class WrapperServiceITest extends AbstractITest {
    //usage of SomeService should not be mocked
    //when calling WrapperService

    //using spy did not work, as suggested in the comments
    @SpyBean
    private SomeService service;;
}

Solution

  • Found a way using a test @Configuration conditional on a property, and overriding that property in the impl with @TestPropertySource:

    public abstrac class AbstractITest {    
        @TestConfiguration //important, do not use @Configuration!
        @ConditionalOnProperty(value = "someservice.mock", matchIfMissing = true)
        public static class SomeServiceMockConfig {
            @MockBean
            private SomeService some;
        }
    }
    
    
    @TestPropertySource(properties = "someservice.mock=false")
    public class WrapperServiceITest extends AbstractITest {
        //SomeService will not be mocked
    }