[英]How to use @SpringBootTest class mockbean in test class?
@SpringBootTest(classes = TestConfig.class)
class ServiceIntegTest {
}
class TestConfig {
@MockBean
RandomExecutor randomExecutor
}
我想在ServiceIntegTest
類中使用RandomExecutor
模擬 bean,怎么做?
我不是在TestConfig
類本身中模擬 bean 的方法,因為在ServiceIntegTest
類中有各種測試,其中RandomExecutor
的方法必須以不同的方式運行。
您不必在配置中使用@MockBean
,您必須在測試類中進行。 然后你可以在一些測試類中模擬它並在其他類中使用真實的實例。
看看@MockBean
的基本用法: https ://www.infoworld.com/article/3543268/junit-5-tutorial-part-2-unit-testing-spring-mvc-with-junit-5.html
您可以像使用@Mock
一樣使用 MockBean,它只是被注入到您用於測試的 spring 上下文中。
@SpringBootTest
class ServiceIntegTest {
@MockBean RandomExecutor randomExecutor;
// this service gets autowired from your actual implementation,
// but injected with the mock bean you declared above
@Autowired
YourService underTest;
@Test
void verifyValueUsed() {
final int mockedValue = 5;
when(randomExecutor.getThreadCount()).thenReturn(mockedValue);
int result = underTest.getExecutorThreads();
assertThat(result).isEqualTo(mockedValue);
}
@Test
void verifyExecutorCalled() {
underTest.performAction("argument");
verify(randomExecutor).executorMethod("argument");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.