是否可以用真实的@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;;
}
答案 0 :(得分:1)
找到了一种方法,该方法使用基于属性的测试@Configuration
,并使用@TestPropertySource
在impl中覆盖该属性:
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
}
答案 1 :(得分:0)