We have a scenario where there are three individual unit tests needed to be executed in Java. So, we will be using Junit as unit testing framework to achieve this task. Lets see with an example
Before using Junit :
Test1.java
1 2 3 4 5 6 7 8 9 10 11 |
Class Test1{ Public static void main(String args[]) { System.out.println("First Test is Executed"); } } |
OUTPUT :
Test2.java
1 2 3 4 5 6 7 8 9 10 11 |
Class Test2{ Public static void main(String args[]) { System.out.println("Second Test is Executed"); } } |
OUTPUT :
Test3.java
1 2 3 4 5 6 7 8 9 10 11 |
Class Test3{ Public static void main(String args[]) { System.out.println(“Third Test is Executed”); } } |
OUTPUT :
Junit-Example3
Observations Without Using Junit :
1.If we want to execute all the three tests Test1,Test2 and Test3 then we need go individually to each and every class to execute the files.
2.No Reporting mechanism, like how many passed or failed status we cannot capture.
By using Junit, both the above will be addressed.
After Using JUnit :
We are making each java file as an @Test and executing our unit tests as below.
Step 1 : Write the First JUnit Test by importing packages
Import the below package, which contains @Test annotation. If we want to use any methods available in JUnit, we need to import that respective packages.
import org.junit.Test;
Step 2 : Define the @Test annotation method using Junit
Place every java file code within @Test as per the above Test1,Test2,Test3.java files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
@Test public void Test1() { System.out.println(“First Test is Executed”); } @Test public void Test2() { System.out.println(“Second Test is Executed”); } @Test public void Test3() { System.out.println(“Third Test is Executed”); } |
Step 3 : let’s collate all the code into single step
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import org.junit.Test; public class junit_AllMethods { @Test public void Test1() { System.out.println("First Test is Executed"); } @Test public void Test2() { System.out.println("Second Test is Executed"); } @Test public void Test3() { System.out.println("Third Test is Executed"); } } |
OUTPUT :
JUnit-AllExamples-Methods
Step 4 : Execute the Test using Junit from Eclipse
Step 5 : Result from Junit
Observations After Using Junit :
No main method i.e Public static void main(String args[]) is used.
Result is generated by integrating JUnit with Java.