View Javadoc
1   /*
2    * Copyright 2018 SPF4J.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * @author Zoltan Farkas
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     * See JUnit doc if overwriting...
41     * @param notifier
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  }