简体   繁体   中英

running @Test one by one using reflection

I'm trying to run a package with many unit tests (one by one, not as a class) using reflection, So when I get all the @Test methods that needs to be run I try to do

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

But the class returned in packageAndClass has @Before, @BeforeClass methods (that also might be in its superclass)

So when running the code above I get all the tests running and fail(because some of their values are assigned in the @Before and @BeforeClass methods) But when running it from eclipse (select the test method name -> right click -> run as -> Junit test) They all pass (runing together or one by one) Is there an api of Request that will run the before methods?

Why are you doing that? JUnit is supposed to run the tests for you!

I ran the following test with 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");
    }
}

and the output was :

beforeClass
before
oneTest
after
afterClass
result true

Are you really sure that the methods are not run ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM