Table of contents
1.
Introduction
2.
What is JUnit Annotations?
3.
JUnit Annotations Example
3.1.
JunitAnnotationsExample.Java
3.1.1.
Output
3.2.
TestRunner.java
3.2.1.
Output
4.
JUnit Assert Class
5.
JUnit Test Cases Class
6.
JUnit TestResult Class
7.
JUnit Test Suite Class
8.
Frequently Asked Questions
8.1.
What are JUnit tests?
8.2.
What does @Test annotation do?
8.3.
What are annotations in JUnit?
8.4.
What is @test annotation in JUnit?
8.5.
What are the three basic JUnit annotations?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

JUnit Annotations

Introduction

Testing is used to check whether the application achieves all the requirements, serves the user with expected functionality and the correct use cases. In other words, testing is done to check the behaviour of the application. The entire code is divided into a few parts based on different properties. These units are called Tests. But how do we write tests? Do we have any frameworks for that? 

Yes, there’s a framework “JUnit” available to perform testing in Java. All tests are specified using annotations before classes and methods. 

JUnit Annotations

Let’s explore what annotations are and how to use them in this article.

What is JUnit Annotations?

The JUnit annotations are predefined texts provided by Java API, which helps JVM to recognize the type of method or class for testing. In other words, they are used to specify or declare the methods or classes with few properties like testing, disabling tests, ignoring tests, etc. We need to install the JUnit dependencies first to use JUnit annotations for testing. You can use Maven to install these dependencies. Check out this article for more details about installing Maven dependencies.

Annotations Description
@Test Represents the method or class as a test block, also accepts parameters.
@Before The method with this annotation gets executed before all the other tests.
@After The method with this annotation gets executed after all the other tests are executed.
@Ignore It is used to ignore a few test statements during execution.
@Disabled Used to disable the tests from execution, but the corresponding reports of the tests are still generated.

Now that we know about annotations and what we use them for let's learn how to use them in our code.

JUnit Annotations Example

Step 1: Let’s understand this with junit annotations example in java

JunitAnnotationsExample.Java

import static org.junit.Assert.assertEquals; 
import static org.junit.Assert.assertFalse; 
import java.util.ArrayList; 

import org.junit.After; 
import org.junit.AfterClass; 
import org.junit.Before; 
import org.junit.BeforeClass; 
import org.junit.Ignore; 
import org.junit.Test; 

public class JunitAnnotationsExample {

    @Test 
    public void m1() { 
        Boolean value = false; 
        assertFalse(value); 
        System.out.println("@Test annotation") 
    } 

    @After 
    public void m1() { 
        list.clear(); 
        System.out.println("@After annotation");
    }

    @Before 
    public void m3() { 
        System.out.println("@Before annotation"); 
    }

    @Ignore 
    public void m4() { 
        System.out.println("@Ignore);// this execution is ignored 
    } 
}
You can also try this code with Online Java Compiler
Run Code

 

We created a few test methods using the annotations @Test,  @After, @Before, and @Ignore annotations in the above code. It gives the following output. 

Output

@Before annotation 
@Test annotation
@After annotation

 

  1. The test method m3() with @Before annotation gets executed before all the other methods.
  2. The method m1() with @Test gets executed and prints the output.
  3. The @Ignore annotation ignores the method, so it does not perform the test, and as a result, no output is given by the method. 
  4. After all the methods are executed, the @After annotation executes the method m2().

 

Step 2: Let’s create a testrunner.java class to execute above test:

TestRunner.java

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(JUnitAnnotationsExample.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
    }
}

 

Output

Before test
Successful test
After test
Before test
Failing test
After test
Before test
After test
Before test
After test


As we can see, the @Before and @After methods are executed before and after each test, respectively. The @Test methods that are not annotated with @Ignore or @Disabled are executed normally. The @Ignore method is ignored and the @Disabled method is skipped. If a @Test method fails, the exception is caught and printed in the test runner output.

JUnit Assert Class

It is an utility class in JUnit framework used for performing various types of assertions to verify expected results in unit testing. It provides various static methods to compare actual and expected values, throw exceptions based on the outcome of the comparison, and report test failures.

 

The org.junit.Assert class provides a set of static assertion methods that can be used in JUnit tests to verify expected results. Here are some of the commonly used assertion methods provided by the Assert class:

S.No. Method Description

1

assertEquals(expected, actual) Checks that two objects are equal

2

assertNotEquals(expected, actual) Checks that two objects are not equal

3

assertArrayEquals(expected, actual) Checks that two arrays are equal

4

assertTrue(condition) Checks that a condition is true

5

assertFalse(condition) Checks that a condition is false

6

assertNull(object) Checks that an object is null

7

assertNotNull(object) Checks that an object is not null

8

assertSame(expected, actual) Checks that two objects refer to the same object

9

assertNotSame(expected, actual) Checks that two objects do not refer to the same object

JUnit Test Cases Class

In JUnit, the TestCase class in the org.junit.TestCase package allows us to run multiple tests. We can mark public void methods as test cases by attaching the @Test annotation to them. The TestCase class provides several methods that are useful for setting up and executing tests, as well as for releasing any resources used during testing.

The org.junit.TestCase class provides several methods that are used to report the results of running JUnit tests. Here are some of the important methods:

S.No. Method Description

1

countTestCases() Counts the number of test cases executed by the run(TestResult tr) method

2

createResult() Creates a TestResult object

3

getName()  Returns the name of the TestCase as a string

4

run() Executes a test and returns a TestResult object.

5

run(TestResult result) Executes a test using a TestResult object but doesn't return anything.

6

setName(String name) Sets the name of the TestCase.

7

setUp() Used to write resource association code, such as creating a database connection.

8

tearDown() Used to write resource release code, such as releasing a database connection after performing a transaction operation.

JUnit TestResult Class

In JUnit, the TestResult class is used to manage and report the results of a test run. It is part of the org.junit package and provides methods for tracking the number of tests that pass or fail, as well as for reporting on the time taken to run the tests.

The org.junit.TestResult class provides several methods that are used to report the results of running JUnit tests. Here are some of the important methods:

S.No. Method Description

1

runCount() This method returns the total number of tests that were run.

2

failureCount() This method returns the number of failures that occurred while running the tests.

3

errorCount() This method returns the number of errors that occurred while running the tests.

4

wasSuccessful() This method returns true if all the tests completed successfully (i.e., no errors or failures occurred).

5

addListener(TestListener listener) This method registers a TestListener

6

stop() This method marks that the test run should stop.

7

removeListener(TestListener listener) This method unregisters a TestListener

 

JUnit Test Suite Class

A JUnit test suite class is a Java class that allows you to group multiple JUnit test classes together into a single suite, which can be executed together as a single unit. The purpose of creating a test suite is to organize related tests together and to execute them in a specific order.

The org.junit.TestSuite class provides several methods that are used to report the results of running JUnit tests. Here are some of the important methods:

S.No. Method Description

1

addTest(Test test) This method adds a new test case or test suite to the current test suite.

2

addTestSuite(Class<?> testClass) This method adds all the test cases in a given test class to the current test suite.

3

countTestCases() This method returns the number of test cases in the current test suite.

4

getName() This method returns the name of the current test suite.

5

run(TestResult result) This method runs all the test cases in the current test suite and reports the results to the given TestResult object.

6

testAt(int index) This method returns the test case at the given index in the current test suite.

7

testCount() This method returns the number of test cases in the current test suite.

8

tests() This method returns an enumeration of all the test cases in the current test suite.

9

toString() This method returns a string representation of the current test suite.

Check out JUnit Interview Questions here.

Frequently Asked Questions

What are JUnit tests?

A test in JUnit is a method or class used only for testing. These are called  Test methods or Tests classes. The tests contain the code used for testing the behaviour of the application.

What does @Test annotation do?

The @Test annotation indicates that the method or class is a test block, and the code inside it is run to test the code. It helps the JVM recognize the block as a test block and perform the testing on that particular method.

What are annotations in JUnit?

JUnit annotations are predefined texts provided by Java API, which helps the JVM recognize the type of method for testing. The most used annotations like @Test, @Before, @Ignore, etc.

What is @test annotation in JUnit?

The @Test annotation is used in JUnit to mark a method as a test method. When JUnit runs the test class, it looks for methods annotated with @Test and executes them. Test methods typically call methods under test and make assertions about the results.

What are the three basic JUnit annotations?

The three basic JUnit annotations that are commonly used to write test methods: @Test, @Before and @After. By using these annotations, JUnit makes it easy to write and execute test methods in a consistent and repeatable way.

Conclusion

Let's discuss the article in brief for a better understanding.

  • The JUnit annotations are predefined texts provided by Java API, which helps JVM to recognize the type of method or class for testing.
  • We can install the dependencies necessary for JUnit testing using Maven.
  • The most used and valid annotations of JUnit are @Test, @Before, @After, @Ignore, @Disabled, @AfterClass, @Tag, etc.


Hey Ninjas! Don’t stop here; check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems.

Happy Learning!

Live masterclass