How to replace a @MockBean?

membersound :

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 :

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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103677&siteId=1