• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.net;
6 
7 import androidx.annotation.NonNull;
8 
9 import org.junit.rules.TestRule;
10 import org.junit.runner.Description;
11 import org.junit.runners.model.Statement;
12 
13 import org.chromium.net.impl.CronetLogger;
14 import org.chromium.net.impl.CronetLoggerFactory.SwapLoggerForTesting;
15 
16 /**
17  * Custom TestRule that instantiates a new fake CronetLogger for each test.
18  * @param <T> The actual type of the class extending CronetLogger.
19  */
20 public class CronetLoggerTestRule<T extends CronetLogger> implements TestRule {
21     private Class<T> mTestLoggerClazz;
22 
23     // Expose the fake logger to the test.
24     public T mTestLogger;
25 
CronetLoggerTestRule(@onNull Class<T> testLoggerClazz)26     public CronetLoggerTestRule(@NonNull Class<T> testLoggerClazz) {
27         if (testLoggerClazz == null) {
28             throw new NullPointerException("TestLoggerClazz is required.");
29         }
30 
31         mTestLoggerClazz = testLoggerClazz;
32     }
33 
34     @Override
apply(final Statement base, final Description desc)35     public Statement apply(final Statement base, final Description desc) {
36         return new Statement() {
37             @Override
38             public void evaluate() throws Throwable {
39                 try (SwapLoggerForTesting swapper = buildSwapper()) {
40                     base.evaluate();
41                 } finally {
42                     mTestLogger = null;
43                 }
44             }
45         };
46     }
47 
48     private SwapLoggerForTesting buildSwapper() {
49         assert mTestLoggerClazz != null;
50 
51         try {
52             mTestLogger = mTestLoggerClazz.getConstructor().newInstance();
53             return new SwapLoggerForTesting(mTestLogger);
54         } catch (ReflectiveOperationException e) {
55             throw new IllegalArgumentException(
56                     "CronetTestBase#runTest failed while swapping TestLogger.", e);
57         }
58     }
59 }
60