gpt4 book ai didi

java - 如何替换@MockBean?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:46:57 26 4
gpt4 key购买 nike

是否可以用真正的@Bean替换继承的@MockBean

我有一个抽象类,它为所有 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;;
}

最佳答案

找到了一种方法,使用以属性为条件的测试 @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
}

关于java - 如何替换@MockBean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51706004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com