xref: /aosp_15_r20/external/cronet/base/test/android/javatests/src/org/chromium/base/test/util/JniMocker.java (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2018 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.base.test.util;
6 
7 import org.jni_zero.JniStaticTestMocker;
8 import org.jni_zero.NativeMethods;
9 import org.junit.rules.ExternalResource;
10 
11 import java.util.ArrayList;
12 
13 /** A test rule to set up and tear down native implementation mocks. */
14 public class JniMocker extends ExternalResource {
15     private final ArrayList<JniStaticTestMocker> mHooks = new ArrayList<>();
16 
17     /**
18      * Sets the native implementation of the class using a JniStaticTestMocker
19      *
20      * All TEST_HOOKS set with this function will have their test instance
21      * set to null after each test is run.
22      *
23      * @param T    Interface type that implements {@link NativeMethods}
24      * @param hook Instance of the corresponding JniStaticTestMocker in the
25      *             wrapper class generated by the JNI annotation processor
26      * @param testInst Mock instance of type T which will be set as the
27      *                 native implementation to be used in tests.
28      */
mock(JniStaticTestMocker<T> hook, T testInst)29     public <T> void mock(JniStaticTestMocker<T> hook, T testInst) {
30         hook.setInstanceForTesting(testInst);
31         mHooks.add(hook);
32     }
33 
34     @Override
35     @SuppressWarnings("unchecked")
after()36     protected void after() {
37         for (JniStaticTestMocker hook : mHooks) {
38             hook.setInstanceForTesting(null);
39         }
40         mHooks.clear();
41     }
42 }
43