Introduction
JUnit is a framework in Java used for unit testing. It is vital in the development of test-driven development. It is part of the xUnit frameworks. We link the JUnit as a JAR file at compile time. JUnit5 resides under the org.junit.jupiter package in Java.
import org.junit.jupiter.api.*;The Assert class in JUnit provides the developer with a set of various Assertion methods to choose from. The developer can record the failed or negative Assertions in JUnit. The Assert class is provided in the Java lang package,
public class assertExample extends java. lang.Object
Example
First, we will create our Java file and name it assertionExample.java.
assertionExample.java
import org.junit.Test;
import static org.junit.Assert.*;
public class assertionExample {
@Test
public void funcAssertions() {
//test data
String str1 = new String ("some text");
String str2 = new String ("some text");
String str3 = null;
String str4 = "some text";
String str5 = "some text";
int num1 = 12;
int num2 = 20;
String[] arr1 = {"first", "second", "third"};
String[] arr2 = {"first", "second", "third"};
//will check the objects are equal
assertEquals(str1, str2);
//will check the condition is true
assertTrue (num1 < num2);
//will check the condition is false
assertFalse(num1 > num2);
//will check the object isn't null
assertNotNull(str1);
//will check the object is null
assertNull(str3);
//will check if the objects point to the same object
assertSame(str4,str5);
//will check if the objects don’t point to the same object
assertNotSame(str1,str3);
//will check if the arrays are equal to each other.
assertArrayEquals(arr1, arr2);
}
}Second, we will create our runTest.java file to execute the test cases.
runTest.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class runTest {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(funcAssertions.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
} In the above example, we used multiple assertion methods and passed various values to the functions to check the functioning of each.
Check out JUnit Interview Questions here.




