Hey everyone in this article, Let’s write the very first JUnit 5 test case with easy to understanding example.
Read More:
- Check the Complete JUnit 5 Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Spring Boot JdbcTemplate Tutorials
- Check the Complete Spring Boot and Data JPA Tutorials
- Check the Complete Spring MVC Tutorials
- Check the Complete JSP Tutorials
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
Consider the following example, the method getMovies()
will return the empty list.
package in.bushansirgur;
import java.util.Collections;
import java.util.List;
public class Movies {
public List getMovies() {
return Collections.emptyList();
}
}
Now we want to write a JUnit test case to test whether the method getMovies()
should return an empty list or not
Development Steps
A test case is broken down into the following 3 parts
- Setup the data that our test case needs
- Call the method being tested
- Perform the assertions to verify if the expected behavior is correct
This is also called AAA (Arrange, Act and Assert)
Success Scenario
package in.bushansirgur;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
class MoviesTest {
@Test
void testMovies() {
Movies m = new Movies();
List list = m.getMovies();
assertTrue(list.isEmpty(), () -> "Movies should be empty");
}
}
@Test
annotation indicates that the method is the Junit test case. If you notice that we have used @Test
annotation from org.unit.jupiter.api.Test
the package. In the earlier versions of JUnit, this annotation was from org.junit.Test
the package. So to write JUnit 5 test cases we have to use org.unit.jupiter.api.Test
annotation.
JUnit 5 has trimmed down assertions support. There is no assertThat()
method in JUnit 5. It is expected that you will use a third-party assertion library like Hamcrest or AssertJ. In the code, we have used the inbuilt assertion assertTrue()
, which tests whether the condition is true or not.
Now that run the test case, our test case should pass.
Failure Scenario
Inside the getMovies()
method, return null instead of returning the empty list.
package in.bushansirgur;
import java.util.Collections;
import java.util.List;
public class Movies {
public List getMovies() {
return null;
}
}
Now that run the test case, our test case should fail
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.