Rerun Failed JUnit Tests

Hello Friends,

Many times Selenium tests are getting failed due to no reason… as UI tests are fragile in nature.

There are many uncertainties like slow response, browser issues… and many more.

Generally we use readily available Test frameworks like JUnit & TestNG to write test cases. TestNG framework has lot off cool features like rerun test, dependency test and many more… but still many of us have JUnit as first choice.


JUnit frame work does not provide any direct feature to rerun the failed tests. So problem is

How we can rerun Failed test in JUnit?



JUnit provides a Interface TestRule, by implementing this we can apply rule for running the test. We have used same class to solve our problem, Please have a look below code snippet in which have created Class Retry which implements the TestRule interface.

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

 * Created by Kirtesh on 20-02-2015.
public class Retry implements TestRule {
    private int retryCount;

    public Retry(int retryCount) {
        this.retryCount = retryCount;

    public Statement apply(Statement base, Description description) {
        return statement(base, description);
    private Statement statement(final Statement base, final Description description) {
        return new Statement() {
            public void evaluate() throws Throwable {
                Throwable caughtThrowable = null;

                // implement retry logic here
                for (int i = 0; i < retryCount; i++) {
                    try {
                    } catch (Throwable t) {
                        caughtThrowable = t;

                        //  System.out.println(": run " + (i+1) + " failed");
                        System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
                System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
                throw caughtThrowable;

That’s it.. you can directly copy above class & use this rule in your junit test… look in to below test

    @Rule public Retry retry = new Retry(3);
    public void myWebDriverTest(){

above test will get rerun if it get fails for 3 time, 3 is the number which you can set in @Rule Retry…


Hope this may hep you…..

Keep exploring… Keep automating….


One thought on “Rerun Failed JUnit Tests

  1. julie August 27, 2016 / 4:21 am

    It’s so cool. I just copied the code. and it works magically. thanks a lot.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s