@SpringBootTest(classes = TestConfig.class)
class ServiceIntegTest {
}
class TestConfig {
@MockBean
RandomExecutor randomExecutor
}
I want to use RandomExecutor
mock bean in ServiceIntegTest
class, how to do it ?
I am not mocking methods of the bean in TestConfig
class itself, because in ServiceIntegTest
class there are various tests in which methods of RandomExecutor
have to behave in different ways.
You do not have to @MockBean
in your config, you have to do it in the test class. Then you can mock it in some test classes and use a real instance in others.
Have a look at a basic usage of @MockBean
: https://www.infoworld.com/article/3543268/junit-5-tutorial-part-2-unit-testing-spring-mvc-with-junit-5.html
You use a MockBean as you would a @Mock
It just get injected into a spring context you're using for your test.
@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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.