如何替换@MockBean?
How to replace a @MockBean?
是否可以用真正的 @Bean
替换继承的 @MockBean
?
我有一个摘要 class,它为所有 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;;
}
使用@SpyBean 来使用真正的bean。
找到了一种方法,使用测试 @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
}
是否可以用真正的 @Bean
替换继承的 @MockBean
?
我有一个摘要 class,它为所有 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;;
}
使用@SpyBean 来使用真正的bean。
找到了一种方法,使用测试 @Configuration
以 属性 为条件,并用 @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
}