0

我正在尝试使用反射运行一个包含许多单元测试的包(一个接一个,而不是一个类),所以当我得到所有需要运行的 @Test 方法时,我尝试做

Result result = new JUnitCore().run(Request.method(Class
                                .forName(packageAndClass),getTestName()));

但是在 packageAndClass 中返回的类有 @Before、@BeforeClass 方法(也可能在它的超类中)

因此,当运行上面的代码时,我让所有测试都运行并失败(因为它们的一些值是在 @Before 和 @BeforeClass 方法中分配的)但是当从 eclipse 运行它时(选择测试方法名称->右键单击->运行as -> Junit test)它们都通过了(一起运行或一个接一个运行)是否有一个请求的api可以运行之前的方法?

4

2 回答 2

3

你为什么这样做?JUnit 应该为您运行测试!

于 2012-09-03T07:22:05.547 回答
0

我用 junit 4.9 运行了以下测试:

public class RunOneTest {
    public static void main(final String[] args) {
        final Result result = new JUnitCore().run(Request.method(RunOneTest.class, "oneTest"));
        System.out.println("result " + result.wasSuccessful());
    }

    @Test
    public void oneTest() throws Exception {
        System.out.println("oneTest");
    }

    @Test
    public void anotherTest() throws Exception {
        System.out.println("anotherTest");
    }

    @Before
    public void before() {
        System.out.println("before");
    }

    @BeforeClass
    public static void beforeClass() {
        System.out.println("beforeClass");
    }

    @After
    public void after() {
        System.out.println("after");
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("afterClass");
    }
}

输出是:

beforeClass
before
oneTest
after
afterClass
result true

你真的确定这些方法没有运行吗?

于 2012-09-03T14:34:37.433 回答