JUnit Assert Methods Example

JUnit Assert Methods Example | It is used to validate the Test, whether the current test is pass or fail. Here, the excepted value is compared with the actual result. Also see:-

Junit 5 has provided class: Assertions (org.junit.jupiter.api) which contains all static method “assert methods”.

Assert methods are used to compare expected values with actual results. If matching test PASS, else test FAIL.

assertEquals(expected, actual):- This method is used to compare expected value with actual value. It has multiple overloaded methods, therefore it can accept any data type.

Create a new Maven project and add the junit-jupiter-engine dependency:-

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.10.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Create a class inside src/test/java folder.

package com.knowprogram.test;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class TestMessage {

    @Test
    public void testA() {
        String expected = "HELLO";
        String actual = "HELLO";
        Assertions.assertEquals(expected, actual);
    }

}

Select the class, and run it as a JUnit test. Inside the JUnit console, it will show whether the test was PASSED or FAILED.

If we want our custom message in case the test fails then we can write:-

assertEquals(expected, actual, "Data May not be matching");

Write a Message class inside src/main/java folder:-

package com.knowprogram.service;

public class Message {
    
    public String showMsg(String name) {
        return "Welcome to " + name;
    }
}

To test the Message#showMsg() method, create a class TestMessage in the src/test/java folder and write a method testShowMsg() as follows:-

package com.knowprogram.test;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

import com.knowprogram.service.Message;

public class TestMessage {

    @Test
    public void testShowMsg() {
        Message m = new Message();
        String expected = "Welcome to SAM";
        String actual = m.showMsg("SAM");
        assertEquals(expected, actual);
    }

}

Object creation and data initialization must be done before Unit testing.

package com.knowprogram.test;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.knowprogram.service.Message;

public class TestMessage {

    // declare variables
    private Message m;
    private String expected;
    private String actual;

    // provide initial data
    @BeforeEach
    public void setup() {
        m = new Message();
        expected = "Welcome to SAM";
        actual = "";
    }

    // do unit test
    @Test
    public void testShowMsg() {
        actual = m.showMsg("SAM");
        assertEquals(expected, actual, "Data May not be matching");
    }

    // clear heap data/clear memory
    @AfterEach
    public void clean() {
        m = null;
        expected = actual = null;
    }

}

assertNotNull(object): This method is used to specify that the given object is not a null value. If the object holds some data then the test passes else the test fails.

assertNull(object): It indicates the given object is null, and else the test fails.

Add the MySQL dependencies:-

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

Create a class to get the MySQL DB connection:-

package com.knowprogram.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbConnection {
    public Connection getConnection() {
        Connection con = null;
        try {
            // con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
            // "root");
            DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }
}

Test the class:-

package com.knowprogram.test;

import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.sql.Connection;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.knowprogram.util.DbConnection;

public class TestDBConnection {

    private DbConnection dbConnection = null;
    private Connection connection = null;

    @BeforeEach
    public void setUp() {
        dbConnection = new DbConnection();
    }

    @Test
    public void testGetConnection() {
        connection = dbConnection.getConnection();
        // expected connection is not null
        assertNotNull(connection, "Connection Is Not Created, Please check!");
    }

    @AfterEach
    public void cleanUp() {
        dbConnection = null;
        connection = null;
    }

}

assertDoesNotThrow(Executable): This is used to specify that our method call is not throwing any exception, else if it throwing then the test fails.

Executable is a functional interface having an abstract method:- void execute() throws Throwable So, lambda expression looks like: () -> { }

Before checking the connection, let us check whether any exception is thrown or not.

public class DbConnection {
    public Connection getConnection() throws Exception {
        Connection con = null;
        try {
            // modify with wrong username or password to get the exception
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root1", "root1");
        } catch (Exception e) {
            throw e;
        }
        return con;
    }

}

Unit test code in TestDBConnection class:-

@Test
public void testGetConnection() {
    assertDoesNotThrow(() -> {
        connection = dbConnection.getConnection();
    });
    assertNotNull(connection, "Connection Is Not Created, Please check!");
}

assertSame(obj1, obj2):- This method is used to test the given two references are pointed to one object, is yes then the test passes else test fails.

What is the difference between assertSame() and assertEquals()? The assertSame() method compares two object references whereas the assertEquals() method compares data.

fail(): This is used for testing multiple conditions, if they are not met then manually fail the test case.

package com.knowprogram.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbConUtil {

    private static Connection con;

    // singleton
    static {
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return con;
    }
}

Test the singleton behavior:-

package com.knowprogram.test;

import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.fail;

import java.sql.Connection;

import org.junit.jupiter.api.Test;

import com.knowprogram.util.DbConUtil;

public class TestDbConUtil {

    @Test
    public void testGetConnection() {
        Connection con1 = DbConUtil.getConnection();
        Connection con2 = DbConUtil.getConnection();
        if(con1 == null || con2 == null) {
            // test case is failed
            fail("Connections are not created");
        }
        assertSame(con1, con2, "May not be same connection");
    }

}

assertArrayEquals():- To compare data of two arrays.

public class TestSample {
    @Test
    public void testNormal() {
        int expected[] = {10,20, 30};
        int actual[] = {10, 20, 45};
        assertArrayEquals(expected, actual);
    }
}

assertTrue()/assertFalse(): These methods are used to test one Boolean condition/expression/value.

assertTrue(): Boolean value is expected as True, else test fails.
assertFalse(): Boolean value is expected as False, else test fail.

@Test
public void testNormal() {
    boolean exist = true;
    assertTrue(exist, "Data may not exist");
}

assertThrows(): Expecting that our logic throws one exception as T type. Syntax:-
assertThrows(ExpectedExceptionType.class, () -> {// our logic})

@Test
public void testNormal() {
    assertThrows(NullPointerException.class, () -> {
        // throw new NullPointerException();
        throw new ArrayIndexOutOfBoundsException();
    });
}

assertAll(Executable… executables): This is used to group multiple assert test methods and execute once. If all are passed then the test is passed, if at least one is failed then the test is failed.

package com.knowprogram.test;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.fail;

import java.sql.Connection;

import org.junit.jupiter.api.Test;

import com.knowprogram.util.DbConUtil;

public class TestSample {
    @Test
    public void testNormal() {
        assertAll(() -> {
            assertNotNull(DbConUtil.getConnection());
        }, () -> {
            Connection con1 = DbConUtil.getConnection();
            Connection con2 = DbConUtil.getConnection();
            assertSame(con1, con2);
        }, () -> {
            Connection con1 = DbConUtil.getConnection();
            Connection con2 = DbConUtil.getConnection();
            if(con1 == null || con2==null) {
                fail();
            }
        });
    }
}

assertTimout():- To check whether business method execution is completed in the specified time or not.

public class ServiceDemo {
    public String showMsg(String name) {
        try {
            // 3 seconds
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Welcome to " + name;
    }
}
public class TestSerivceDemo {
    @Test
    public void testShowMsgWithTimer() {
        ServiceDemo demo = new ServiceDemo();
        // 2 seconds
        assertTimeout(Duration.ofMillis(2000), () -> {
            demo.showMsg("KnowProgram");
        });
    }
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *