1 /*
2  * Copyright (C) 2023 The Android Open Source Project
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 com.android.adservices.common;
17 
18 import android.annotation.CallSuper;
19 import android.content.Context;
20 
21 import com.android.adservices.shared.testing.common.ApplicationContextSingletonRule;
22 
23 import org.junit.Before;
24 import org.junit.Rule;
25 
26 /**
27  * Base class for all unit tests.
28  *
29  * <p>Contains only the bare minimum functionality required by them, like custom JUnit rules.
30  *
31  * <p>In fact, this class "reserves" the first 11 rules (as defined by order 0-10), so subclasses
32  * should start defining rules with {@code order = 11}.
33  */
34 public abstract class AdServicesUnitTestCase extends AdServicesTestCase {
35 
36     private static final String APP_CONTEXT_MSG = "should use existing mAppContext instead";
37 
38     @Rule(order = 5)
39     public final ApplicationContextSingletonRule appContext =
40             new ApplicationContextSingletonRule(/* restoreAfter= */ false);
41 
42     /**
43      * Reference to the application context of this test's instrumentation package (as defined by
44      * {@link android.app.Instrumentation#getContext()}.
45      *
46      * <p>In other words, it's the same as {@code mContext.getApplicationContext()}.
47      */
48     protected Context mAppContext;
49 
50     @Before
setAdServicesUnitTestCaseFixtures()51     public final void setAdServicesUnitTestCaseFixtures() {
52         mAppContext = mContext.getApplicationContext();
53     }
54 
55     @CallSuper
56     @Override
assertValidTestCaseFixtures()57     protected void assertValidTestCaseFixtures() throws Exception {
58         assertTestClassHasNoFieldsFromSuperclass(AdServicesUnitTestCase.class, "mAppContext");
59         assertTestClassHasNoSuchField("APPLICATION_CONTEXT", APP_CONTEXT_MSG);
60         assertTestClassHasNoSuchField("mApplicationContext", APP_CONTEXT_MSG);
61     }
62 }
63