Junit SuiteClasses with a static list of classes

☆樱花仙子☆ 提交于 2019-11-28 04:26:34

问题


SuiteClasses will work just fine with a list of classes like {Test1.class,Test2.class}, but when I try to generate a static list of classes, it says incompatible types: required java.lang.Class<?> but found java.lang.Class<?>[]

What am I missing?

@RunWith(Suite.class)

@Suite.SuiteClasses(TestSuite.classes)
public class TestSuite {

    public static Class<?> [] classes;

    static {
       classes = new Class<?> [1];
       classes[0] = MyTest.class;
    }
}

回答1:


That shouldn't really work. You are intended to put the array within the annotation as a constant. Even if you got past this problem, the compiler would reject it. What you need to do is this:

@RunWith(Suite.class)

@Suite.SuiteClasses({MyTest.class, MyOtherTest.class})
public static class TestSuite {
}

Note the squiggly brackets.

I'm sure what you are trying to get at is to be able to build the list of classes in the suite dynamically.

I submitted a request to them to allow that, but in the mean time the only way to do it is to subclass the Suite class like so:

public class DynamicSuite extends Suite {

    public DynamicSuite(Class<?> setupClass) throws InitializationError {
       super(setupClass, DynamicSuiteBuilder.suite());
    }
}


@RunWith(DynamicSuite.class)
public class DynamicSuiteBuilder {
   public static Class[] suite() {
         //Generate class array here.
   }
}



回答2:


@SuiteClasses is a class annotation defined in JUnit 4.4 in org.junit.runners.Suite.SuiteClasses. It allows you to define a suite class as described in the previous question.

By the way, the API document of JUnit 4.4 has a major typo for the org.junit.runners.Suite class (Suite.html).

Using Suite as a runner allows you to manually build a suite containing tests from many classes. It is the JUnit 4 equivalent of the JUnit 3.8.x static Test suite() method. To use it, annotate a class with @RunWith(Suite.class) and @SuiteClasses(TestClass1.class, ...). When you run this class, it will run all the tests in all the suite classes.

@SuiteClasses(TestClass1.class, ...) should be changed to @Suite.SuiteClasses({TestClass1.class, ...}).

Someone provided wrong information on build test suite in JUnit 4.4. Do not follow this:

JUnit provides tools to define the suite to be run and to display its results. To run tests and see the results on the console, run:

org.junit.runner.TextListener.run(TestClass1.class, ...);


来源:https://stackoverflow.com/questions/1070202/junit-suiteclasses-with-a-static-list-of-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!