JUnit TestName Rule Example


JUnit encapsulates each action in the form of a Statement. JUnit offers a way to alter test’s behavior by letting us provide a list of rules that can be applied to a test or suite execution.

The Statement object that executes the method or suite is passed to each rule which in turn retruns a modified Statement. The modified statement becomes the input to the next rule.

We provide rules using Rule annotation. Each rule member is an implementation of TestRule.

In this example we will use TestName rule to capture the name of the current test executing.

TestName Example

In the below example, we have used @Rule annotated field and assigned it an instance of TestName. The field must be a non-static public method.
We get the current test name using testName.getMethodName(). See setup() where we print the test name.


package com.javarticles.junit;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

public class TestNameExample {
    public final TestName testName = new TestName();
    public void setup() throws Exception {
        System.out.println("Setup for test '" + testName.getMethodName() + "'");
    public void createTest() {       
    public void retrieveTest() {       
    public void updateTest() {       
    public void deleteTest() {       


Setup for test 'updateTest'
Setup for test 'retrieveTest'
Setup for test 'createTest'
Setup for test 'deleteTest'

Download the source code

This was an example of JUnit TestName rule.

You can download the source code here: junitTestNameRuleExample.zip

Comments are closed.