java.lang.Exception错误:测试类应该恰好具有一个公共构造函数

时间:2018-07-18 09:28:29

标签: java unit-testing exception junit

运行JUnit测试时出现异常。

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

下面是我的代码段,有什么想法吗?

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

我正在使用Gradle运行JUnit测试。这是一个Java项目,它立即失败。 我已经尝试了无数次尝试,但无济于事。乐意提供更多详细信息。

1 个答案:

答案 0 :(得分:0)

消息很清楚:

  

java.lang.Exception:测试类应该只有一个公共类   构造函数

您将单元测试类与Rule测试类合并到同一类AllTests中。
您应该在自己的类中定义规则并删除此构造函数:

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