ERROR with java.lang.Exception: Test class should have exactly one public constructor

I am getting an exception when I run my JUnit tests.

java.lang.Exception: Test class should have exactly one public constructor

Below is my code snippet, any ideas?

package com.tests;    

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


public class AllTests implements TestRule {
    private int retryCount;

    private AllTests(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() {
            @Override
            public void evaluate() throws Throwable {
                Throwable caughtThrowable = null;

                // implement retry logic here
                for (int i = 0; i < retryCount; i++) {
                    try {
                        base.evaluate();
                        return;
                    }
                    catch (Throwable t) {
                        caughtThrowable = t;
                        System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
                    }
                }
                System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
                throw caughtThrowable;
            }
        };
    }

    @Rule
    public AllTests allTests = new AllTests(3);

    @ClassRule
    public static DockerComposeRule docker = wi.getDocker(logs);

    @Override
    public DockerComposeRule getDocker() {
        return docker;
    }

    @Test
    public void myFirstTest() throws Exception {
        // Test code here...
    }
}

I am running a JUnit test, with Gradle. It is a Java project and it fails straightaway. I have tried numerous things but to no avail. Happy to provide more details if you want.

1 answer

  • answered 2018-07-18 09:29 davidxxx

    The message is clear :

    java.lang.Exception: Test class should have exactly one public constructor

    You merged the unit test class with the Rule test class in the same class : AllTests.
    You should define your rule in its own class and remove this constructor :

    private AllTests(int retryCount) {
        this.retryCount = retryCount;
    }