Show List

Assertions in JUnit

JUnit assertions are methods provided by the JUnit framework that allow developers to check the expected outcome of a test case. If the outcome of a test case doesn't match the expected result, the test case fails. JUnit provides several assertions to cover different types of test cases.

Here are some examples of JUnit assertions:

assertTrue, assertFalse

assertTrue and assertFalse are used to check if the condition is true or false. These can have one or more parameters. 
  • assertTrue(boolean condition)
  • assertTrue(boolean condition, String message) . Here message will be returned as failure message if the condition is not true
Here is an example:
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class DemoTest {

@Test
public void testWithAssertFalse(){
boolean condition = false;
assertFalse(condition);
}

@Test
public void testWithAssertTrue(){
boolean condition = false;
assertTrue(condition, "Provided condition is false");
}


}

assertNull, assertNotNull

assertNull and assertNotNull are to check if the supplied value is null or not null.
@Test
public void testWithAssertNull() {
Object val1 = null;
assertNull(val1);
}

@Test
public void testWithAssertNotNull() {
Object val1 = "A";
assertNotNull(val1, "Provided value is Null");
}

assertSame, assertNotSame

assertSame and assertNotSame are to evaluate whether two variables are pointing to the same object.
@Test
public void testWithAssertSame() {
String val1 = new String("A");
String val2 = new String("B");
String val3 = val1;

assertSame(val1, val3);
assertNotSame(val1, val2);
}

assertEquals, assertArrayEquals, assertIterableEquals

assertEquals is used to evaluate whether two objects or values are equal. assertArrayEquals is to test equality of arrays. 

assertIterableEquals is to evaluate two iterables. Here the iterables do not need to be of same type but the elements should be same.
@Test
public void testWithAssertEqual() {
String val1 = new String("A");
String val2 = new String("B");
String val3 = val1;

assertEquals(val1, val3);
assertNotEquals(val1, val2);
}

@Test
public void testWithAssertArrayEqual() {
char[] arr1 = {'a', 'b', 'c', 'd'};
char[] arr2 = {'a', 'b', 'c', 'd'};

assertArrayEquals(arr1, arr2);
}

@Test
public void testWithAssertIterablesEqual() {
Iterable<String> arrayList = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterable<String> linkedList = new LinkedList<>(Arrays.asList("A", "B", "C"));

assertIterableEquals(arrayList, linkedList);
}

fail

fail method is used to fail a test based on scenario. 
@Test
public void testFailInAScenerio() {
int val1 = 1;
int val2 = 2;
if (val1 != val2) {
fail("Received values do not match");
}
}
Test Output:
org.opentest4j.AssertionFailedError: Received values do not match

	at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
	at org.junit.jupiter.api.Assertions.fail(Assertions.java:117)
	at DemoTest.testFailInAScenerio(DemoTest.java:77)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

assertAll

assertAll is used to asserting a set of properties that belong together as a unit. assertAll checks all the assertions passed to it no matter how many fail.

For example if all the address fields are to be validated, in stead of writing the separate conditions, we can group them together under assertAll.

Seperate conditions:
Address address = obj.getAaddress();
assertEquals("City Name", address.getCity());
assertEquals("Street Name", address.getStreet());
assertEquals("Street Number", address.getNumber());
Using assertAll
Address address = obj.getAaddress();
assertAll("Should all address fields correctly",
    () -> assertEquals("City Name", address.getCity()),
    () -> assertEquals("Street Name", address.getStreet()),
    () -> assertEquals("Street Number", address.getNumber())
);

assertThrows

assertThrows asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.If no exception is thrown, or if an exception of a different type is thrown, this method will fail. 

Here are two examples. In the first one we are only checking that the provided exception is thrown. In the second example we are also checking the exception message.

Example 1
@Test
public void testAssertThrows() {
String str = null;
assertThrows(NullPointerException.class, () -> str.length());
}
Example 2
class Dummy {
void throwExp() throws Exception {
throw new Exception("Custom Exception");
}
}
@Test
public void testAssertThrowsAndThenAssert() {
Dummy dummyClass = new Dummy();
Exception exception = assertThrows(Exception.class, () -> dummyClass.throwExp());
assertEquals("Custom Exception", exception.getMessage());
}

assertTimeout, assertTimeoutPreemptively

assertTimeout and assertTimeoutPreemptively methods are used to check that the given task gets completed within the specified time.

Difference between the two is that assertTimeoutPreemptively will also abort the task execution if it is not completed within the specified time.

Example:
@Test
public void testAssertTimeout() {
assertTimeout(Duration.ofMillis(300), () -> {
Thread.sleep(200);
return "result";
});
}

@Test
public void testAssertTimeoutPreemptively() {
assertTimeoutPreemptively(Duration.ofMillis(300), () -> {
Thread.sleep(200);
return "result";
});
}

Source Code:
https://github.com/it-code-lab/Unit-Test-Demo

    Leave a Comment


  • captcha text