Junit Tutorial: A Complete guide for beginners

Last updated on Jul 13,2020 4.8K Views

Junit Tutorial: A Complete guide for beginners

edureka.co

JUnit is a testing framework for Java programming language. It is important for test-driven development. Through the medium of this JUnit tutorial, I will guide your way to spread your wings in the field of testing Java frameworks. 

I’ll be discussing the topics in this manner:

So, let get started!

JUnit Tutorial: What is JUnit? 

JUnit is an open source Unit Testing Framework for Java. It is important in the development of test-driven frameworks. It is considered as an instance of xUnit architecture. As the name suggests it is used for testing a small chunk of code or a unit. 

Unit Testing is used to verify a small chunk of code by creating a path, function or a method. The term “unit” existed even before earlier the object-oriented era. It is basically a natural abstraction of an object-oriented system i.e. a Java class or object (its instantiated form).

JUnit promotes the idea of “Test first, code later”, which emphasizes on setting up the test data for a piece of code that can be tested first and then implemented. 

Advantages

Features

JUnit Tutorial: JUnit rules

It annotates rules and methods that return a Rule. A method must be public, not static, and must return a subtype of TestRule or MethodRule.

A JUnit 4 rule is a component that intercepts the test method calls and allows you to do perform some action before a test method is run and after a test method has been run. All JUnit 4 rule classes must implement this interface org.junit.rules.TestRule.

  1. Add a public field to your test class and ensure that the type of that field is a subtype of TestRule.

  2. Annotate the field with the @Rule annotation.

Note: JUnit 4 requires that rule fields are public, they aren’t static, and are a subtype of TestRule.

JUnit 5 rule: To handle the issue, you have several possible approaches to keep the JUnit 4 way. You can rewrite the @Rule as an extension.

JUnit Tutorial: The JUnit framework

JUnit is a Regression Testing framework which is used to implement unit testing in Java, to accelerate programming speed and increase the quality of code. This framework also allows quick and easy generation of test data and test cases. 

Unit test framework provides these important features:

Test fixtures

A fixture is a fixed state of a set of objects which is used as a baseline for running the test cases. The major purpose of a test fixture is to ensure that there is a well-known and fixed environment in which tests are run so that results are repeatable.

Let’s understand this with an example:

The below code is designed to execute two test cases on a simple file.

public class TestCaseFile
{
private File output;
output = new File(...);
output.delete();
public void testFile1()
{
//Code to verify Test Case 1
}
output.delete();
output = new File(...);
public void testFile2()
{
//Code to verify Test Case 2
}
output.delete();
}

Notice the few issues here:

Comparing the same code using JUnit

public class TestCaseFile
{
private File output;
@Before public void createOutputFile()
{
output = new File(...);
}
@After public void deleteOutputFile()
{
output.delete();
}
@Test public void testFile1()
{
// code for test case objective
}
@Test public void testFile2()
{
// code for test case objective
}
}

The code is far more readable and maintainable. The code structure above is a Text fixture.

Test suites

If you want to execute multiple test cases in a specific order, it can be done by combining all the test cases in a single origin. This origin is called the test suites.

A test suite bundles a few unit test cases and runs them together.

To run the suite test, you need to annotate a class using below-mentioned annotations:

  1. @Runwith(Suite.class)
  2. @SuiteClasses(test1.class,test2.class……) or @Suite.SuiteClasses ({test1.class, test2.class……})

Test Runner

The test runner is used for executing the test cases.

JUnit provides a tool for the execution of the test cases.

JUnit Classes

JUnit classes are used in writing and testing JUnits. Some of the important classes are:

JUnit Tutorial: How to Set Up JUnit

JUnit is a Testing framework used to test the Java-based application. So before installing JUnit, you need to configure and verify java development kit (JDK) in your machine.

Follow these steps to complete your Java installation.

OSTaskCommand
WindowsOpen Command Console/ cmdc:> java -version
LinuxOpen Command Terminal/cmd$ java -version
MacOpen Terminalmachine:~ john$ java -version

Next, click on New and add the variable and value.

  1. Provide the variable name as “JUNIT_HOME“.
  2. Also, provide JUnit value as the path where you have copied JUnit jar files.
  3. Click on OK.

It will create a new system variable with the given name and value.

After creating JUNIT_HOME, create another variable with the name CLASSPATH. Follow the below steps:

 In this step, point out JUNIT_HOME to JUnit.jar which is placed in the JUnit folder as given below:

  1. Variable Name: JUNIT_HOME
  2. Variable Value: %CLASSPATH%;%JUNIT_HOME%JUnit4.10.jar;.;
  3. Click on the OK button.

Once you click on the ‘OK‘ button, you can verify that a new environment variable called “CLASSPATH” can be seen under the system variable.

Install Eclipse IDE

Please refer this to download Eclipse IDE on your system.

How to install JUnit jar files in Eclipse

  1. Right click on the project.
  2. Click on “build path”.
  3. Click on “Configure build path”.

Add external JUnit jar files that you have downloaded.

And add JUnit libraries to your project by following this method:

Then find JUnit and click on it.

Now that you have understood how to set up JUnit on your system, let’s move ahead and learn how to write a simple JUnit program.

JUnit Tutorial: How to run a simple JUnit program

I’ll create two classes in order to give you an idea of how JUnit programs can be written.

First class provides simple assert statements in order to verify JUnit setup.


package Edureka;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Java {
@Test
public void testSetup() {
String str= "I know to set up JUnit on my system";
assertEquals("I know to set up JUnit on my system",str);
}
}

Next up, I’ll create another class to execute the above test.


package Edureka;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class JunitClass {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(Java.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println("Result=="+result.wasSuccessful());
}
}

Output:

Now that you’ve learned how to write a simple JUnit program, let’s understand how assert statements work in JUnit.

JUnit Tutorial: JUnit annotations

JUnit framework is built on annotations. An annotation is a special form of syntactic metadata that can be added to the java source code for better code readability. These annotations provide the following information about test methods:

These are the following list of annotations and their meaning in JUnit:

Sr.No.AnnotationsDescription
1@Test

The Test annotation tells JUnit that the public void method can be run as a test case.

2@Before

Annotating a public void method with @Before causes that method to be run before each Test method.

3@After

If you allocate external resources in a Before method, you need to release them after the test runs. Annotating the method with @After causes that method to be run after the Test method.

4@BeforeClass

Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class.

5@AfterClass

This will perform the method after all tests are run. This can be used to perform clean-up activities.

6@Ignore

The Ignore annotation is used to ignore the test and that test will not be executed.

JUnit Tutorial: JUnit Assert statements

Assert is a method used in determining pass or fail status of a test case. In JUnit, all the assertions are in the Assert class. This class provides a set of assertion methods which are useful for writing tests. Only failed assertions are recorded. 

Sr.No.MethodDescription
1void assertEquals(boolean expected, boolean actual)

Checks that two primitives/objects are equal.

2void assertTrue(boolean condition)

Checks whether the condition is true.

3void assertFalse(boolean condition)

Checks whether the condition is false.

4void assertNotNull(Object object)

Checks whether an object isn’t null.

5void assertNull(Object object)

Checks whether an object is null.

6void assertSame(object1, object2)

The assertSame() method tests if two object references point to the same object.

7void assertNotSame(object1, object2)

The assertNotSame() method tests if two object references do not point to the same object.

8void assertArrayEquals(expectedArray, resultArray)

The assertArrayEquals() method will test whether two arrays are equal to each other.

 Let’s take a look at an example:

import org.junit.Test;
import static org.junit.Assert.*;
public class TestAssertions
{
@Test public void testAssertions()
{
//test data
String str1 = new String ("edu");
String str2 = new String ("edu");
String str3 = null;
String str4 = "edu";
String str5 = "edu";
int val1 = 5;
int val2 = 6;
String[] expectedArray = {"one", "two", "three"};
String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(str1, str2);
//Check that a condition is true
assertTrue (val1 < val2);
//Check that a condition is false
assertFalse(val1 > val2);
//Check that an object isn't null
assertNotNull(str1);
//Check that an object is null
assertNull(str3);
//Check if two object references point to the same object
assertSame(str4,str5);
//Check if two object references not point to the same object
assertNotSame(str1,str3);
//Check whether two arrays are equal to each other.
assertArrayEquals(expectedArray, resultArray);
}
}

Now, write another program that helps in executing the test.

 import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner()
{
public static void main(String[] args)
{
Result result = JUnitCore.runClasses(TestAssertions.class);
for (Failure failure : result.getFailures())
{
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
} 

The output is: true

Now, let’s take a look at the exceptions that occur during the execution of the process.

JUnit Tutorial: Exceptions

JUnit provides an option of tracing the exception that occurs in the code. You can test whether the code throws the desired exception. The expected parameter is used along with @Test annotation.

While testing for an exception, you need to ensure that the exception class you are providing in that optional parameter of the @Test annotation is the same. This is because you are expecting an exception from the method you are testing, otherwise your JUnit test would fail.

Ex: @Test(expected=IllegalArgumentException.class)

By using the “expected” parameter, you can specify the exception name that your test may throw. In the above example, you are using “IllegalArgumentException” which will be thrown by the test if a developer uses an argument which is not permitted.

Let’s understand the parameterized test in JUnit.

JUnit Tutorial: Parameterized test

JUnit 4 has introduced a new feature called Parameterized tests. This test allows a developer to run the same test over and over again using different values. You have to follow these steps in order to create a parameterized test. 

Let’s take a look at an example.

import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.Before;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class PrimeNumber
{
private Integer i;
private Boolean expectedResult;
private PrimeNumberChecker primeNumberChecker;
@Before public void initialize()
{
primeNumberChecker = new PrimeNumberChecker();
}
// Each parameter should be placed as an argument here
// Every time runner triggers, it will pass the arguments
// from parameters we defined in primeNumbers() method
public PrimeNumberCheckerTest(Integer i, Boolean expectedResult)
{
this.i= i;
this.expectedResult = expectedResult;
}
@Parameterized.Parameters
public static Collection primeNumbers()
{
return Arrays.asList(new Object[][]
{
{ 2, true },
{ 6, false },
{ 19, true },
{ 22, false },
{ 23, true }
}
);
}
// This test will run 4 times since we have 5 parameters defined
@Test public void PrimeNumberCheckerTest()
{
System.out.println("Parameterized Number is : " + i);
assertEquals(expectedResult, primeNumberChecker.validate(i));
}
} 

Create another class TestRunner to compile the program.

 import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class Runner
{
public static void main(String[] args)
{
Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class);
for (Failure failure : result.getFailures())
{
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
} 

The output is: Parameterized Number is: 2
Parameterized Number is : 6
Parameterized Number is : 19
Parameterized Number is : 22
Parameterized Number is : 23
true

Let’s understand the final topic of this discussion, JUnit vs TestNG. 

JUnit Tutorial: JUnit vs TestNG

TestNG and JUnit, both are the well-known terminologies when you talk about Software testing frameworks. TestNG is almost similar to JUnit except for certain functionalities, I’ll compare JUnit and TestNG based on their features.

FeaturesJUnit

TestNG

Suite Test

                  Yes

Yes

Annotation support

                 Yes

            Yes

Ignore test

    @ignore

@Test(enable=false)

Execution before and after all tests in the suite

        No

@BeforeSuite, @AfterSuite,@BeforTest, @AfterTest

Dependency test

        No

Yes

Parameterized Test

@RunWith and @Parameter   @DataProvider

With this, we come to the end of “JUnit Tutorial” blog. I Hope you guys enjoyed this article and understood why JUnit plays a major role in testing a Java framework.

Now that you have understood how JUnit works, check out the Software Testing Certification Course by Edureka, a trusted online learning company with a network of more than 650,000 satisfied learners spread across the globe. This course is designed to introduce you to the complete Selenium features and its importance in testing software.

Got a question for us? Please mention it in the comments section of “JUnit Tutorial” and we will get back to you.

BROWSE COURSES