Spring boot 2 with Junit 5 and Mockito 2 for unit testing and integration test

Here we will explain to use Junit 5 and Mockito 2 with Spring boot 2 when it comes to unit testing and integration tests .

mockito-junit5-logo3-horiz.png

First if you are interested to read more about Junit 5 and Mockito 2 , please check the following links :

  1. Junit 5: https://junit.org/junit5/
  2. Mockito 2 : https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2

Here we will show to the following :

  1. Gradle configuration for Junit 5 with spring boot 2
  2. How to define and execute unit test with Junit 5 and mockito 2
  3. How to define and execute spring boot integration test with Junit 5

Gradle configuration for Junit 5 with spring boot 2:

To add the needed Junit 5 dependencies , here what you need to add , whole code sample is on GitHub :


dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter'
testImplementation('org.junit.jupiter:junit-jupiter-api:5.2.0')
testCompile('org.junit.jupiter:junit-jupiter-params:5.2.0')
testRuntime('org.junit.jupiter:junit-jupiter-engine:5.2.0')
testCompile "org.mockito:mockito-core:2.+"
testCompile('org.mockito:mockito-junit-jupiter:2.18.3')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

view raw

build.groovy

hosted with ❤ by GitHub

How to define and execute unit test with Junit 5 and mockito 2:

To run Junit 5 test case with Mockito2 , we use Juipter extensions support and here we will use mockito extension , the purpose of Junit 5 extensions is to extend the behavior of test classes or methods, and these can be reused for multiple tests.


@ExtendWith(MockitoExtension.class)
@DisplayName("Spring boot 2 mockito2 Junit5 example")
public class ShowServiceTests {
private static final String MOCK_OUTPUT = "Mocked show label";
@Mock
private TextService textService;
@InjectMocks
private ShowService showService;
@BeforeEach
void setMockOutput() {
when(textService.getText()).thenReturn(MOCK_OUTPUT);
}
@Test
@DisplayName("Mock the output of the text service using mockito")
public void contextLoads() {
assertEquals(showService.getShowLable(), MOCK_OUTPUT);
}
}

view raw

Junit5Test.java

hosted with ❤ by GitHub

How to define and execute spring boot integration test with Junit 5:

Now if we want to call the real service not  the mocked one for integration test with Junit 5 , we will use spring extension to support that and now your integration test is running with Junit 5 support as well.


@ExtendWith(SpringExtension.class)
@SpringBootTest
public class SpringBootJunit5IntegrationTest {
@Autowired
private ShowService showService;
@Test
@DisplayName("Integration test which will get the actual output of text service")
public void contextLoads() {
assertEquals(showService.getShowLable(), ORIGINAL_OUTPUT);
}
}

Hoping this cover the starting jump when you want to use Junit 5 in your spring boot application .

The whole code sample is on GitHub

Leave a Reply