oneself
oneself

Reputation: 40231

Invoke a specific JUnit test programmatically

I would like to run a specific JUnit test method programmatically. I know I can run the whole test using the following code snippet:

Class<?> test = Class.forName("MyTestClass");
JUnitCore junit = new JUnitCore();
Result result = junit.run(test);

However, I would like to run a specific method within this test class which contains multiple methods.

It would also be fantastic if I could control the setUp/tearDown behaviour.

Thank you

Upvotes: 4

Views: 4326

Answers (1)

Art Licis
Art Licis

Reputation: 3679

There's an overloaded JUnitCore#run method version that accepts Request. While Request has Request#method factory method to:

Create a Request that, when processed, will run a single test. This is done by filtering out all other tests. This method is used to support rerunning single tests.

If you need to control #setUp / #tearDown (i.e., methods marked with @Before and/or @After annotations) you can extend the class and override methods you need to alter.

Upvotes: 6

Related Questions