Home > Back-end >  How to use @SpringBootTest class mockbean in test class?
How to use @SpringBootTest class mockbean in test class?

Time:07-18


@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.

CodePudding user response:

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

CodePudding user response:

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");
  }
}
  • Related