2
votes

I want to call the RunNotifier of a JUnitCore. It's called fNotifier and is initiated in the JUnitCore class. Source:

https://github.com/KentBeck/junit/blob/master/src/main/java/org/junit/runner/JUnitCore.java

Can I get this by reflection somehow, or is there any other way I can call this RunNotifier.

I want to use his pleaseStop() method.

2
This is possible (in general) and may require reflection, but can you give us some specific details about what you're trying to do? For instance, how are you running the test(s)? From Eclipse, from the command line, from maven? Also, if you could give some details about why you want to stop a test, which you can just do by throwing an exception in your test method?Matthew Farwell
I start them with a JUnitCore.run() inside my prog which is started from command line. Then I want to have a option to stop execution without closing my prog. So I want to stop the whole testrun not just a single test.arket

2 Answers

2
votes

Using reflection isn't the best method, but you can do it something like this:

public static void main(String[] args) throws Exception {
    Computer computer = new Computer();

    JUnitCore jUnitCore = new JUnitCore();
    Field field = JUnitCore.class.getDeclaredField("fNotifier");
    field.setAccessible(true);
    RunNotifier runNotifier = (RunNotifier) field.get(jUnitCore);
    runNotifier.pleaseStop();
    jUnitCore.run(computer, BeforeAfterTest.class, AssertionErrorTest.class);
}

This will throw a org.junit.runner.notification.StoppedByUserException.

If you want more flexibility or control, a better way to do the above is to just copy the bits you want from JUnitCore into your class, and then you've got direct control over the notifier, and listeners, etc. This is the nicest way to do it. JUnitCore isn't really deisgned to be extended.

1
votes

Using JUnit 4.1.2 the field name has changed to 'notifier :

 Field field = JUnitCore.class.getDeclaredField("notifier");