Creating test case in JUnit 5
- To create a Junit Test case file, right click on the src folder and go to New -> Junit Test Case.
- Once clicked that, a new dialog box will be displayed to enter the test case class details.
- Enter the Test class name.
- Enter the Utilities class name under the `class under test` textbox, the name should be along with the package name.
- Click on next.
- Now you need to select the methods you are going to test.
- I have selected the two static methods of the class.
- Now add the below content to the test class.
- The below content, uses the basic @Test annotation to denote a method as a Junit Test case.
- In Junit 5 we don’t have to make our methods and class as public, so by default its just has the default scope to the current package.
Java
// sample test package package com.example.test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.example.utils.Utilities; import org.junit.jupiter.api.Test; // A JUnit Test class to test // Utilities Class class UtilitiesTest { // test 1 for checking the static isPrime method // from Utilities class // Test annotations are being used to create JUnit tests @Test void testIsPrime1(){ assertTrue(Utilities.isPrime( 13 )); } // test 2 to check the isprime method @Test void testIsPrime2(){ assertFalse(Utilities.isPrime( 18 )); } // test 1 to check the static isEven method // from Utilities class @Test void testIsEven1(){ assertFalse(Utilities.isEven( 19 )); } // test 2 to check the isEven method @Test void testIsEven2(){ assertTrue(Utilities.isEven( 80 )); } } |
- Save and close the Test class file.
- Let’s see how we can run the Junit5 test and see the output.
JUnit 5 – Execute Test in Eclipse
JUnit is one of the widely used unit testing frameworks for Java-based Applications. We have different versions and upgrades published by JUnit 5, the latest version available in JUnit is JUnit 5. JUnit 5 is the upgraded version of JUnit 4, which is launched to support various latest features of Java like lambda expressions, etc. So, if you want to use JUnit 5 in your testing make sure that you are running a modern version of Java where Java 8 is the minimum version it can be.
Prerequisites
- Junit- Knowledge of Junit is required, as in this article we will be seeing how to execute the Junit test in Eclipse, not how to use Junit.
- Eclipse IDE- You should have installed Eclipse in your system, if not you can easily do it by visiting the Link.