1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.spf4j.test.log.junit4;
17
18 import java.lang.reflect.Field;
19 import java.util.List;
20 import javax.annotation.Nullable;
21 import javax.annotation.concurrent.ThreadSafe;
22 import org.junit.runner.notification.RunListener;
23 import org.junit.runner.notification.RunNotifier;
24 import org.junit.runners.BlockJUnit4ClassRunner;
25 import org.junit.runners.model.InitializationError;
26
27
28
29
30 @ThreadSafe
31 public class Spf4jTestLogJUnitRunner extends BlockJUnit4ClassRunner {
32
33 private static final Field LISTERES_FIELD = getListenersField();
34
35 public Spf4jTestLogJUnitRunner(final Class<?> klass) throws InitializationError {
36 super(klass);
37 }
38
39
40
41
42
43 @Override
44 public synchronized void run(final RunNotifier notifier) {
45 if (LISTERES_FIELD != null) {
46 try {
47 List<RunListener> lstnrs = (List<RunListener>) LISTERES_FIELD.get(notifier);
48 for (RunListener lstnr : lstnrs) {
49 if (lstnr instanceof Spf4jTestLogRunListener) {
50 super.run(notifier);
51 return;
52 }
53 }
54 } catch (IllegalArgumentException | IllegalAccessException ex) {
55 throw new RuntimeException(ex);
56 }
57 }
58 Spf4jTestLogRunListenerSingleton listener = Spf4jTestLogRunListenerSingleton.getOrCreateListenerInstance();
59 notifier.removeListener(listener);
60 notifier.addListener(listener);
61 super.run(notifier);
62 }
63
64 @Nullable
65 private static Field getListenersField() {
66 Field field;
67 try {
68 field = RunNotifier.class.getDeclaredField("listeners");
69 } catch (NoSuchFieldException | SecurityException ex) {
70 return null;
71 }
72 field.setAccessible(true);
73 return field;
74 }
75
76 }