如何替换@MockBean?

mem*_*und 6 java spring spring-boot spring-boot-test

是否可以@MockBean用真实的代替继承的@Bean

我有一个抽象类,它为所有 ITest 定义了许多配置和设置。仅在一次测试中,我想使用真正的 bean,而不使用模拟的 bean。但仍然继承其余的配置。

@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;;
}
Run Code Online (Sandbox Code Playgroud)

mem*_*und 5

找到了一种在属性上使用测试@Configuration条件的方法,并使用以下方法覆盖 impl 中的该属性@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
}
Run Code Online (Sandbox Code Playgroud)