JUnit TestName Rule Example

0

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.

TestNameExample:

package com.javarticles.junit;

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

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

Output:

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

Comments are closed.