JUnit 4 Tutorial – All Tactics are here!

JUnit 4 is one of the most popular unit testing framework which has a significant role in the test-driven development process. In this JUnit 4 tutorial, we will understand and see examples of the below topics.

JUnit 4 Tutorial Prerequisites

Development Kit: JAVA JDK
Java Test Runner: JUnit (http://junit.org/)
IDE: IntelliJ (I prefer IntelliJ) also you can go with Eclipse or Netbeans
Nice to have: Before starting the JUnit tutorial, it is nice to have basic knowledge of JAVA or any other object-oriented programming language. Also, it is better to check the “Quick Start to Selenium WebDriver with JAVA & JUnit & Maven & IntelliJ” tutorial before starting this one.

JUnit 4 Naming Conventions

In general, test classes’ names should be ended with “Test” suffix. Also, it is highly recommended to give a meaningful name for your test classes such as FirefoxOrderCheckTest, ChromeLoginTest, etc… In this way, you can easily understand the functionalities of test classes.

Defining a Test in JUnit 4

To start a JUnit test, you need to annotate a method with @Test annotation. There are many annotations in Junit and I will explain them in the below section but the most critical annotation is “@Test” annotation. This indicates that the following method is a test method. In your test methods, you use “assert” statements to check the conditions that you are testing. It is a very good habit to write a clear message in assert statements that help us to understand the problems easily. I also explained them in the Assertions section.

Most Common JUnit 4 Annotations

JUnit comprises some annotations that help us to run JUnit tests more easily and make them more readable. By using JUnit annotations, we can mark the methods as test methods and do various configurations on them. I listed frequently used annotations and their description in the below table and you can find examples of all annotations in the examples section.

Annotation Description
@Test
public void method()

The @Test annotation indicates the following method as a test method.

The following method has to be declared as public void

@Before
public void method()

This method is executed before each test.

It is generally using for setting necessary preconditions.

The following method has to be declared as public void

@After
public void method()

This method is executed after each test.

It is used to delete temporary data, restore default settings.

The following method has to be declared as public void

@BeforeClass
public static void method()

The following static method is executed once, before the start of all tests.

It is generally using for highly intensive operations such as DB connections.

The following method has to be declared as public static void

@AfterClass
public static void method()

The following static method is executed once after all tests have been completed.

It is generally using for clean-up activities such as disconnect from a database.

The following method has to be declared as public static void

@Ignore
public static void method()

This annotation is useful when you want temporarily disable the execution of a specific test.

The following method has to be declared as public static void

@Test (expected = Exception.class) If the method does not throw the given exception, the test will fail.
@Test(timeout=500) If the method takes longer than 500 milliseconds, the test will fail.

JUnit 4 Assertions

 JUnit’s assert class consists of several static methods to test specific conditions. Assert statements generally, starts with the assert keyword and then check specific conditions. You can specify meaningful error messages to understand what did go wrong after the test execution. The general form of these methods is (“Error Message”, “Expected Value”, “Actual Value”). They compare expected value with actual value. If expected and actual values do not match then the assert method throws “AssertionException” and you will see you error message output of IDE console. All assertions explanations are described in the JUnit website (http://junit.org/apidocs/org/junit/Assert.html). In this tutorial, I will go with the important ones and give examples of all of them in the examples section.

  Assert Methods & Description & Syntax
1 void assertEquals (“Message”, boolean expected, boolean actual)
 

It compares that the given two values are the same.

Syntax: assertEquals(“Str1 is not equal to str 2”, str1, str2);

2 void assertTrue(“Message”, boolean condition)
 

It checks that the boolean condition is true.

Syntax: assertTrue(“Bolean expression is not TRUE! Please check it!”, val1 < val2);

3 void assertFalse(“Message”, boolean condition)
 

It checks that the boolean condition is false.

Sytnax: assertTrue(“Bolean expression is not FALSE! Please check it!”, val1 < val2);

4 void assertNull(“Message”, Object object)
 

It checks that the object is null

Syntax: assertNotNull(“Object is not NULL! Pls check it!”, obj);

5 void assertNotNull(“Message”, Object object)
 

It checks that the object is not null

Syntax: assertNotNull(“Object is NULL! Pls check it!”, obj);

6 void assertSame(“Message”, boolean condition)
 

It checks that two objects refer to the same object

Sytnax: assertSame(obj1,obj2);

7 void assertNotSame(boolean condition)
 

It checks that two objects do not refer to the same object

Syntax: assertNotSame(obj1,obj2);

Test execution order

JUnit tests are running in an arbitrary order. If you want to run your tests in a fixed order, you should use @FixMethodOrder(MethodSorters.NAME_ASCENDING) annotation. With this annotation, you can lexically sort and test the methods in ascending order. It is shown below screenshot.

Annotation and Assertion Examples

1) Creating a JUnit Package and JUnit Test Classes

Creating a JAVA project is described in the “Quick Start to Selenium WebDriver with JAVA & JUnit & Maven & IntelliJ” tutorial. Thus, I will not start from the beginning.

Right-click “java” folder, then go to “New” and click “Package”.

junit_2

Give a package name to combine all JUnit tests in that package as shown below.

junit_3

For annotation and assertion examples, right-click to “junitexamples” package and go to “New” then click “Java Class”.

junit_4

Then, for the annotation test, give a “JunitAnnotationTest” name to the class (java file).

junit_5

For assertion examples, give a “JunitAssertionTest” name to the class (java file).

junit_6

Finally, our project structure will look like below.

junit_7

2) Annotation Example

When you run the below code, you will see that

@BeforeClass runs only once before the all tests started

@Before runs before each test started

@Test defined attached method is a test method.

@After runs after each test finished

@AfterClass runs only once after all tests are finished.

In the below code, I used “@FixMethodOrder(MethodSorters.NAME_ASCENDING)” annotation and lexically ordered test names to run the tests in lexical order.

I mean that all test names are started with T01_…, then T02_…, then T03…

By using “@FixMethodOrder(MethodSorters.NAME_ASCENDING)” annotation, these test cases will run in the following order T01 → T02 → T03

~ In the below code, I tried to explain important points with inline comments. ~

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Junit4Annotations {

    static String websiteUrl = null;
    String user = null;

    //It will run only once
    @BeforeClass
    public static void SetInitialValues() {
        websiteUrl = "www.swtestacedemy.com";
        System.out.println("[@BeforeClass] Setting Initial Values...\nWebsite URL is: " + websiteUrl + "\n");
    }

    //It runs before every test. Default user is always Onur
    @Before
    public void setUserInfo() {
        user = "Onur";
        System.out.println("[@Before] Before test set user values.\nDefault user is: " + user + "\n");
    }

    //First test outputs "Ezgi"
    @Test
    public void T01_firstTest() {
        user = "Ezgi";
        System.out.println("[@Test] This is first test and user is: " + user + "\n");
    }

    //Second test outputs "Mike"
    @Test
    public void T02_secondTest() {
        user = "Mike";
        System.out.println("[@Test] This is second test and user is: " + user + "\n");
    }

    //Third test outputs "Onur" because I did not set another name to user value
    @Test
    public void T03_thirdTest() {
        System.out.println("[@Test] This is third test and user is: " + user + "\n");
    }

    //It runs at the end of each test clasess and set user value to null
    @After
    public void afterTest() {
        user = null;
        System.out.println("[@After] This test is finished...\nUser is: " + user + "\n");
    }

    //It runs only once when all test finished
    @AfterClass
    public static void afterClass() {
        System.out.println("[@AfterClass] All tests are finished!\n");
    }
}

The output of Annotation Example:

[@BeforeClass] Setting Initial Values...
Website URL is: www.swtestacedemy.com

[@Before] Before test set user values.
Default user is: Onur

[@Test] This is first test and user is: Ezgi

[@After] This test is finished...
User is: null

[@Before] Before test set user values.
Default user is: Onur

[@Test] This is second test and user is: Mike

[@After] This test is finished...
User is: null

[@Before] Before test set user values.
Default user is: Onur

[@Test] This is third test and user is: Onur

[@After] This test is finished...
User is: null

[@AfterClass] All tests are finished!

3) Assertion Example

In the below example, I wanted to show that all assertions that I explained in the assertions section. You can find detailed information in comment lines. When you run the below code all assertions will pass. Also, you can play with actual and expected values and will see what is going to happen according to your changes.

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Junit4Assertions {

    @Test
    public void T01_assertionExamples() {

        //1)assertEquals
        //Parameters: "message", expected, actual

        //Text Comparison Example
        assertEquals("Text comparison failed!", "Test Text", "Test Text");

        //Computation Comparison
        assertEquals("Computation comparison failed!", 9, 3 + 6);

        //Boolean Comparison
        //3<5 is true and comparison of true==true is true so it will not assert anything.
        assertEquals("Boolean comparison is not Passed!", true, 3 < 5);

        //----------------------------------------------------------------------------------

        //2)assertTrue
        //Parameters: "message", boolean condition
        //If the condition is true, do not assert anything!
        assertTrue("Boolean condition is not TRUE! Pls check it!", 3 < 5);

        //----------------------------------------------------------------------------------

        //3)assertFalse
        //Parameters: "message", boolean condition
        //If the condition is false, do not assert anything!
        assertFalse("Boolean condition is not FALSE! Pls check it!", 3 > 5);

        //----------------------------------------------------------------------------------

        //4)assertNull
        //Parameters: "message", object
        //If object is null, do not assert anything! If it is not null, assert an error message.
        String testObj1 = null;
        assertNull("testObj1 is not null! Pls Check it!", testObj1);

        //----------------------------------------------------------------------------------

        //5)assertNotNull
        //Parameters: "message", object
        //If object is not null, do not assert anything! If it is null, assert an error message.
        String testObj2 = new String("test");
        assertNotNull("testObj2 is null! Pls Check it!", testObj2);

        //----------------------------------------------------------------------------------

        //6)assertSame
        //Parameters: "message", expected, actual
        //If two objects refer to the same object, do not assert anything! If it is not, assert an error message.
        String str1 = "SAME";
        String str2 = "SAME";
        assertSame("Two objects do not refer to the same object!", str1, str2);

        //----------------------------------------------------------------------------------

        //7)assertNotSame
        //Parameters: "message", expected, actual
        //If two objects do not refer to the same object, do not assert anything! If it is not, assert an error message.
        String str3 = "SAME";
        String str4 = "NOT SAME";
        assertNotSame("Two objects refer to the same object!", str3, str4);
    }
}

JUnit 4 Test Suites

If you have more than one test class, you can combine them into a test suite. If you run this test suite, test classes will be executed in the specified order.

I used suites while I was automating www.teknosa.com multiple browsers login test cases. In the following example, I added three login test classes into the test suite and run them all together.

package junit.suites;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import webdriver.testscenarios.loginCheck.LoginCheckChromeTest;
import webdriver.testscenarios.loginCheck.LoginCheckFirefoxTest;
import webdriver.testscenarios.loginCheck.LoginCheckIETest;

@RunWith(Suite.class)
@Suite.SuiteClasses({
        LoginCheckIETest.class,
        LoginCheckFirefoxTest.class,
        LoginCheckChromeTest.class
})
public class LoginCheckForAllBrowsersSuiteTest {
}

You can also see the project architecture below.

junit_8

Github Page

https://github.com/swtestacademy/junit/tree/junit4-overview

Summary

Now you have learned this JUnit 4 tutorial:

  • How to use JUnit 4 annotations in your unit and selenium tests.
  • Meanings of JUnit 4 assertions.
  • How to execute the test in ascending and descending lexical order.
  • You saw some assertion and annotation examples.
  • How to use Junit 4 suites

Other JUnit Articles

Thanks,
Onur Baskirt

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.