Table of contents
1.
Introduction
2.
The org.junit Package
2.1.
Class
2.2.
Annotations
2.3.
Example
3.
The org.junit.runner Package
3.1.
Class
3.2.
Annotations
4.
The org.hamcrest.core Package
4.1.
Class
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Junit Packages

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Junit is an open-source testing framework for programmers working with java. It is one of the primary unit testing frameworks, and the current version is junit 4.

The core Junit Api contains multiple packages and interfaces that you can import in a test suite according to the user requirements. All these packages are essential for performing Unit Testing using Junit. 

Suppose you are unfamiliar with the concept of Unit Testing. In that case, you can check out our article on writing your very first unit test using the Jest testing framework (a testing framework in Javascript) here

The org.junit Package

The org.junit is the core Junit package corresponding to the Junit framework. This package provides all the core classes and annotations of Junit. 

The Classes of this package are as follows:

Class

  1. Assert: Provides a set of assertion methods that you can use for writing tests. That includes methods like assertEqualsassertFalseassetTrue all of these take boolean as a parameter and check against condition to be EqualsTrue, or False, respectively. 
    Other methods like assertNullassertNotNull take objects as parameters to check the Null condition. And fail(), which fails a test with no message. 
  2. Assume: Provides a set of methods used for stating assumptions about conditions in which a test is meaningful.
  3. Test.None: This is the default empty exception.

 

The Junit framework is annotations-based; therefore, the Junit package also includes some annotations. The org.junit package consists of the following annotations:

Annotations

  1. Before: We use this in tests requiring you to create similar objects before running a test.
  2. After: You can use this when you need to release external resources after running a test if you allocate external resources in a Before.
  3. BeforeClass: You can use this when tests need to share a computationally expensive setup (like logging into a database).
  4. AfterClass: You can use this when you need to release expensive external resources after all the tests in the class have run. Suppose you allocate them in a BeforeClass method.
  5. Ignore: Sometimes, you will want to temporarily disable a test or a group of tests to use this method.
  6. Test: This annotation tells JUnit that the public void method to which the Test is attached can run as a test case.

Example

We will try out some of these methods with an elementary example. Firstly let us create a java class file with the test code (example testjunit1.java) in your project directory.

Program

import org.junit.Test;
import static org.junit.Assert.*;

public class testjunit1 {
  @Test
  public void testAdd() {
     //test data
     int num = 5;
     String temp = null;
     String str = "Junit is working fine";

     //check for equality
     assertEquals("Junit is working fine", str);
    
     //check for false condition
     assertFalse(num > 6);

     //check for not null value
     assertNotNull(temp);
  }
}
You can also try this code with Online Java Compiler
Run Code

You can see that we have imported org.junit package at the top level. We have also used Assert class and Test annotation in this class file. Now that we have our class file, we can create a class file (example testrunner1.java) in the same directory.

Program

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

public class testrunner1 {
  public static void main(String[] args) {
     Result result = JUnitCore.runClasses(junittest1.class);
      
     for (Failure failure : result.getFailures()) {
        System.out.println(failure.toString());
     }
      
     System.out.println(result.wasSuccessful());
  }
} 
You can also try this code with Online Java Compiler
Run Code

You can verify the output by firstly running the following command to run the Test Runner classes on the terminal.

WorkingDirectoryPath> javac testjunit1.java testrunner1.java

You can now run the Test Runner that runs the test case. 

C:\JUNIT_WORKSPACE>java TestRunner1

Output

true

The org.junit.runner Package

Another basic Junit package that we used in the example above is org.junit.runner. This package has various essential methods. Runner provides classes that you can use to describe, collect, run and analyze multiple tests. 

Let us summarise the usage of Classes in this package, some used in our example above.

Class

  1. Description:  A Description class describes a test you have run or are going to run.
  2. JUnitCore: The JUnitCore class is a facade for running tests.
  3. Request: A Request gives an abstract description of tests that will run.
  4. Result: A Result class collects and summarises information by running multiple tests.
  5. Runner: A Runner runs tests and, as it does so, notifies a RunNotifier of significant events.

Annotations

  1. RunWith: When you annotate a class with @RunWith or extend a class annotated with @RunWith, JUnit will invoke the class it references to run tests in that class instead of the runner built into JUnit.

The org.hamcrest.core Package

Hamcrest is a vast framework that assists in writing software tests in the Java programming language. It supports creating customized assertion matchers, allowing declaration to define match rules.

Several packages are available in Junit that use org.hamcrest.core. Below are short summaries of the packages that use org.hamcrest.core.

  1. org.hamcrest: The stable API defines Matcher and its associated interfaces and classes. 
  2. org.hamcrest.core: This package provides the fundamental matchers of objects, values, and composite matchers. 
  3. org.junit.matchers: This package provides useful additional Matchers for use with the Assert.assertThat(Object, org.hamcrest.Matcher) statement.

All these packages use classes from the org.hamcrest.core included in their respective packages.

Class

  • AnyOf: org.hamcrest and org.hamcrest.core use this class. It Calculates the logical disjunction of multiple matchers.
assertThat("myValue", allOf(startsWith("my"), containsString("Val")))
You can also try this code with Online Java Compiler
Run Code
  • CombinableMatcher.CombinableBothMatcher: The CoreMatchers.both method in org.hamcrest and the CombinableMatcher.both method in org.hamcrest.core package matches when both of the specified matchers match the examined object. 
assertThat("fab", both(containsString("a")).and(containsString("b")))
You can also try this code with Online Java Compiler
Run Code
  • CombinableMatcher.CombinableEitherMatcher: The CoreMatchers.either method in org.hamcrest and the CombinableMatcher.either method in org.hamcrest.core package matches when either of the specified matchers matches the examined object.
assertThat("fan", either(containsString("a")).and(containsString("b")))
You can also try this code with Online Java Compiler
Run Code
  • SubstringMatcher: This class is used by org.hamcrest.core. This class contains three subclasses StringContainsStringEndsWithStringStartsWith. Tests for argument to be string containing, starting or ending with a substring. 
    Check out JUnit Interview Questions here.

FAQs

  1. Is JUnit part of Java?
    JUnit is a java Unit Testing framework. The first requirement to use JUnit is to install JDK in your system. It is an open-source framework used to write and run repeatable automated tests.
     
  2. What are the advantages of JUnit?
    JUnit is a tool that every developer should learn and use heavily in their daily work. The most important benefits of the JUnit framework are:
    A simple framework for writing automated tests in Java
    Supports test assertions
    Test suite development
    Immediate test reporting
     
  3. What is the limitation of using JUnit?
    Junit is a handy and capable testing framework. It does have some limitations, though.
    It cannot do dependency testing, unlike the TestNG framework.
    It's not suitable for testing larger test suites.
    Unlike TestNG, JUnit cannot perform group testing.
    Can't create test cases HTML reports
     
  4. What does the JUnit test accelerate?
    JUnit Framework accelerates programming speed and increases the quality of code. It also allows quick and easy generation of test data and test cases. 

Key Takeaways

The possibilities of testing with the Junit framework are endless. From core packages like org.junit that provide access to the JUnit framework to essential packages like Runner and Hamcrest, having vital methods in performing unit tests. We have explored some of the major packages and APIs available in the framework. There are many more packages, methods, and classes that you will come across as you start working on more complex test suites. 

Jest is one of the many such testing frameworks that you can use. If you are interested in Unit Testing frameworks, you can check out our article on the Jest framework here.

There is much more to learn, so head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more. Till then, Happy Learning!

Live masterclass