AWS Global Infrastructure

Junit Tutorial: A Complete guide for beginners

Last updated on Jul 13,2020 4.8K Views


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 - JUnit tutorial - EdurekaJUnit 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

  • JUnit provides a text-based command line.
  • It also provides an AWT and Swing-based graphical test reporting mechanism.
  • JUnit is one of the best testing frameworks that can be selected for an efficient testing process.
  • More Application Developer IDEs includes JUnit.
  • The open source community has extended JUnit by implementing a JUnitEE test framework that enables it to test within the application server’s container.
  • This is widely adopted by many organizations around the world for performing unit testing in Java programming language.
  • JUnit has become a benchmark for testing in Java programming language and it is supported by almost all the IDE’s.

Features

  • JUnit tests allow you to write codes faster, which increases quality.
  • It is elegantly simple. It is less complex and takes less time to test an application.
  • Provides annotations to identify test methods.
  • Also provides assertions in order to test for expected results.
  • It provides test runners for running the tests.
  • The tests can be run automatically on JUnit and they check their own results and provide immediate feedback. There is really no need to manually comb through a report of the test results.
  • JUnit tests can be organized into test suites containing test cases.
  • This also helps in showing test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails.

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
  • Test suites
  • Test runners
  • JUnit classes

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.

    • setUp() method, which runs before every test invocation. The annotation @Before is used.
    • tearDown() method, which runs after every test method. The annotation @After is used.

    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:

    • The code is not readable.
    • It is not easy to maintain.
    • When the test suite is complex, the code might contain logical issues.

    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.

    • JUnitCore class is used in order to execute the tests.
    • A method called runClasses which is provided by org.junit.runner.JUnitCore is used to run one or several test cases.
    • The return type of this method is the result object (org.junit.runner.Result), that is used to access information about the tests.

    JUnit Classes

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

    • Assert: It contains a set of assert methods.
    • TestCase: Contains a test case that defines the fixture to run multiple tests.
    • TestResult: It contains methods in order to collect the results of executing a test case.

    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.

    Java SE Development Kit 11- Selenium Installation-Edureka

    • In the next page, select the Accept License Agreement radio button, accept it and click the download link against your matching system configuration.

    • Now to cross-check the installation, just run following command in cmd –java -version. It should display the installed version of Java in your system.

          OSTaskCommand
          WindowsOpen Command Console/ cmdc:> java -version
          LinuxOpen Command Terminal/cmd$ java -version
          MacOpen Terminalmachine:~ john$ java -version
          • You can run the installer once the download is over and follow onscreen instructions.
            • Go to start and search for ‘System’
            • Click on ‘System’
            • Click on ‘Advanced system settings’
            • Click on ‘Environment Variables’ under the ‘Advanced’ tab  as shown below:

          Junit Setup- Junit tutorial - Edureka

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

          Junit setup1 - Junit tutorial - Edureka

          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.

          Setup2 - Junit tutorial - Edureka

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

          Setup3 - Junit tutorial - Edureka

          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”.

          Eclipse - JUnit tutorial - Edureka

          Add external JUnit jar files that you have downloaded.

          Junit jar - Junit tutorial - Edureka

          Junit Setup1 - Junit tutorial - Edureka

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

          Add library- Junit tutorial - Edureka

          Then find JUnit and click on it.

          Junit jar files - JUnit tutorial - Edureka

          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

          • Right click on the src folder to create a new package.
          • Right click on the package in order to create a new class.
          • Start writing the code inside this class.

          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:

          Output - JUnit tutorial - Edureka

          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:

          • The methods that are going to be run before and after test methods.
          • Methods that are run before and after all the methods.
          • The methods or classes that will be ignored during the execution.

          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. 

          • Annotate test class with @RunWith. This specifies that it is a parameterized test.
          • Create a public static method annotated with @Parameters that returns a Collection of Objects in the form of an array as test data set.
          • Create a public constructor that takes in what is equivalent to one row of test data.
          • Create an instance variable for each and every column of test data.
          • Create your test cases using these instance variables as the source of the test data.

          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.

            Comments
            0 Comments

            Join the discussion

            Browse Categories

            Subscribe to our Newsletter, and get personalized recommendations.