Before sversion 2.2.x spring boot has integrated with junit 4.x by default with spring-boot-starter-test. However after 2.2.x up spring-boot has upgraded to included junit 5.x as default of the starter test. In this post- I won’t cover details on junit 5. If you would like to know the benefits of junit 5 over junit 4 and migrate your junit 4 to junit 5, you can read this blog.
- Maven Dependency
if you go to the https://start.spring.io/ and you hit generate then you will see the maven dependency in your default pom.xml file like this.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
As you can see by default spring boot exclude vintage engine. it means - it only support for junit 5. However if you would like to run your old test classes and methods with junit 4, you can remove exclusions. Now we are good to go with junit 5.
2. Write Your Test Class in Spring Boot with JUnit 5
@ExtendWith(SpringExtension.class)
@WebMvcTest(BookController.class)
public class BookControllerTest {
@Autowired
MockMvc mockMvc;
@Test
@DisplayName("Test book controller expect ok")
public void testBookController_Return_OK() throws Exception{
mockMvc.perform(get("/books"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
So now in junit 5 spring boot is using @ExtendWith(SpringExtension.class) instead of @RunWith(SpringRunner.class). @DisplayName is the junit 5 feature.
3. How about You already had JUnit 4
If you already had the old test classes with junit 4 running and you want to use junit 5, what you have to do is removing the exclude vintage engine. So you still be alright to go with junit 4 test and junit 5 classes running together.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Example :
@RunWith(SpringRunner.class)
//@RunWith(MockitoJUnitRunner.class)
public class BookServiceTest {
@InjectMocks
BookService bookService;
@Mock
BookRepository bookRepository;
@Before
public void setUp() {
when(bookRepository.findById(any())).thenReturn(Optional.of(new Book(1, "title", "author", "SNB")));
bookService = new BookService(bookRepository);
}
@Test
public void testOnJunit4() {
Optional<Book> bookOptional = bookService.findBookById(1);
Assertions.assertThat(bookOptional.isPresent()).isEqualTo(true);
}
}
As you can see, I am using @RunWith(SpringRunner.class) and @Before, it’s for junit 4.
Here is the sample code for you to getting start:https://github.com/PheaSoy/spring-boot-2-2-x.