6

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;;
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

5

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
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
0

Use @SpyBean to use the real bean.

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/SpyBean.html

Gundamaiah
  • 780
  • 2
  • 6
  • 30