首页 > 解决方案 > 在 JUnit5 中使用 TestSuites

问题描述

我喜欢用相同的代码测试类似类型的类,所以我不会忘记做一些事情。使用 JUnit4(技术上是 Junit3)我创建了这样的类:

@RunWith(AllTests.class)
public class MyPojoTest {

    public static TestSuite suite() {
        return PojoTestSuite.forPojoClass(MyPojo.class)
            // test Serializable is implemented correctly
            .serializable()
            // test Comparable is implemented correctly
            .comparable()
            // etc.
            .cloneable()
            // creates a junit.framework.TestSuite
            .create();
    }
}

public class PojoTestSuite {

    public static PojoTestSuite forPojoClass(Class<?> pojoClass) {
        return new PojoTestSuite(pojoClass);
    }

    public TestSuite create() {
        final TestSuite suite = new TestSuite();

        suite.addTest(new EqualsTest());
        suite.addTest(new HashCodeTest());

        if (this.serializable) {
            suite.addTest(new SerializeableTest());
        }
        if (this.cloneable) {
            suite.addTest(new CloneableTest());
        }
        if (this.comparable) {
            suite.addTest(new ComparableTest());
        }
        return suite;
    }

    // getters and setters, constructor, ...
}

但是我无法在纯 JUnit4 中实现类似的东西,现在在 JUnit5 中我也找不到类似的东西。

有没有办法使用测试套件来动态创建一组测试?我希望测试尽可能小,因为testEqualsReturnsTrueForSameObject()“失败”比testPojo()“失败”有用得多。

标签: junitjunit5junit-jupiter

解决方案


推荐阅读