HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Junit / JUnit Test Listener – JUnit RunListener Example

JUnit Test Listener – JUnit RunListener Example

Listeners, in general, helps in listening the events on which we are interested. This might be for several reasons. For example, we add listeners to add specific logs, handle UI events in Java GUI programming etc.

JUnit also provide support for adding listeners while executing the tests via RunListener class. This listener can be used for various purposes from improved logging to test specific logic.

1. JUnit RunListener Example

1.1. JUnit test classes

We are writing two test classes below for example only. We will monitor the logs printed for tests written in these classes.

package com.howtodoinjava.junit;

import junit.framework.Assert;

import org.junit.Test;

public class TestFeatureOne {
	@Test
	public void testFirstFeature()
	{
		Assert.assertTrue(true);
	}
}
package com.howtodoinjava.junit;

import junit.framework.Assert;

import org.junit.Ignore;
import org.junit.Test;

public class TestFeatureTwo {
	@Test
	public void testSecondFeature()
	{
		Assert.assertTrue(true);
	}

	@Test
	@Ignore
	public void testSecondFeatureIngored()
	{
		Assert.assertTrue(true);
	}
}

1.2. JUnit test listener

Lets write run listener. This listener will extend the RunListener class provided by JUnit.

We are free to override any number of methods RunListener class from including no method at all.

package com.howtodoinjava.junit.suite;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class ExecutionListener extends RunListener
{
	/**
	 * Called before any tests have been run.
	 * */
	public void testRunStarted(Description description)	throws java.lang.Exception
	{
		System.out.println("Number of tests to execute : " + description.testCount());
	}

	/**
	 *  Called when all tests have finished
	 * */
	public void testRunFinished(Result result) throws java.lang.Exception
	{
		System.out.println("Number of tests executed : " + result.getRunCount());
	}

	/**
	 *  Called when an atomic test is about to be started.
	 * */
	public void testStarted(Description description) throws java.lang.Exception
	{
		System.out.println("Starting execution of test case : "+ description.getMethodName());
	}

	/**
	 *  Called when an atomic test has finished, whether the test succeeds or fails.
	 * */
	public void testFinished(Description description) throws java.lang.Exception
	{
		System.out.println("Finished execution of test case : "+ description.getMethodName());
	}

	/**
	 *  Called when an atomic test fails.
	 * */
	public void testFailure(Failure failure) throws java.lang.Exception
	{
		System.out.println("Execution of test case failed : "+ failure.getMessage());
	}

	/**
	 *  Called when a test will not be run, generally because a test method is annotated with Ignore.
	 * */
	public void testIgnored(Description description) throws java.lang.Exception
	{
		System.out.println("Execution of test case ignored : "+ description.getMethodName());
	}
}

2. JUnit Listener Execution

Now, lets run the tests and observe the listener output.

package com.howtodoinjava.junit.suite;

import org.junit.runner.JUnitCore;

import com.howtodoinjava.junit.TestFeatureOne;
import com.howtodoinjava.junit.TestFeatureTwo;

public class ExecuteWithRunListener
{
	public static void main(String[] args)
	{
		JUnitCore runner = new JUnitCore();
		<strong>//Adding listener here</strong>
		runner.addListener(new ExecutionListener());
		runner.run(TestFeatureOne.class, TestFeatureTwo.class);
	}
}

Program Output.

Number of tests to execute : 3

Starting execution of test case : testFirstFeature
Finished execution of test case : testFirstFeature

Starting execution of test case : testSecondFeature
Finished execution of test case : testSecondFeature

Execution of test case ignored : testSecondFeatureIngored

Number of tests executed : 2

Clearly, adding listener provide extra control on test execution with improved logging support.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Abhinai

    April 25, 2018

    OnFinished and OnFailure methods are not working for me..

    onStart method is executing for me…

  2. Varun

    April 5, 2014

    I am executing my junit tests from ant build.xml. I have created a Listener which should listen to all executing tests. How can I add this listener in my build.xml, as I don’t have ant junitcore object to execute my tests.

    • Lokesh Gupta

      April 5, 2014

      Maybe http://ant.apache.org/manual/Tasks/junit.html#enabletestlistenerevents can help you.

  3. Gui

    November 22, 2013

    How you can have the result (true/false/fail) in testFinished for each atomic test ?

  4. bds

    October 26, 2013

    how and where to add run listener in an existing suite . I have some thousands of test case in an existing frame work . I want to add listen which should run at the end of test to teardown external test data created in third party system

    • Lokesh Gupta

      October 26, 2013

      As you can see that listeners do not take input parameters which bring you some data used in testcase. so it is logically not possible for me to write a teardown method in interceptor.
      Also, writing teardown code for thousands tests in one interceptor, seems bad to me.
      Cleaning up the data should be responsibility of testcase itself, because it knows what is that it is making dirty for others. Use interceptors for logging; or report generation.

Comments are closed on this article!

Search Tutorials

JUnit 5 Tutorial

  • JUnit 5 – Introduction
  • JUnit 5 – Test LifeCycle
  • JUnit 5 – @BeforeAll
  • JUnit 5 – @BeforeEach
  • JUnit 5 – @AfterEach
  • JUnit 5 – @AfterAll
  • JUnit 5 – @RepeatedTest
  • JUnit 5 – @Disabled
  • JUnit 5 – @Tag
  • JUnit 5 – Expected Exception
  • JUnit 5 – Assertions Examples
  • JUnit 5 – Assumptions
  • JUnit 5 – Test Suites
  • JUnit 5 – Gradle Dependency
  • JUnit 5 – Maven Dependency
  • JUnit 5 – Execute Test in Eclipse
  • JUnit 5 – Eclipse Test Templates
  • JUnit 5 vs JUnit 4

JUnit 4 Tutorial

  • JUnit – Introduction
  • JUnit – Test Suite
  • JUnit – Execute with JUnitCore
  • JUnit – Execute with Maven
  • JUnit – org.junit.Assume
  • JUnit – Expected Exceptions
  • JUnit – Listeners
  • JUnit – Force Timeout
  • JUnit – Ordered Tests
  • JUnit – Parameterized Tests
  • Junit – @Theory And @DataPoints
  • JUnit – TemporaryFolder @Rule

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)