MockitoHelper.java revision aa383cca668afd8578a6e007c3ea360768dc52f6
1/*
2 * Copyright (C) 2015 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
17package com.android.server.telecom.tests;
18
19import com.android.server.telecom.Log;
20
21import android.annotation.TargetApi;
22import android.content.Context;
23import android.os.Looper;
24
25/**
26 * Helper for Mockito-based test cases.
27 */
28public final class MockitoHelper {
29    private static final String DEXCACHE = "dexmaker.dexcache";
30
31    private Thread mRequestThread;
32    private ClassLoader mRequestThreadOriginalClassLoader;
33    private ClassLoader mMainThreadOriginalClassLoader;
34
35    /**
36     * Creates a new helper, which in turn will set the context classloader so
37     * it can load Mockito resources.
38     *
39     * @param packageClass test case class
40     */
41    public void setUp(Context context, Class<?> packageClass) throws Exception {
42        // makes a copy of the context classloader
43        mRequestThread = Thread.currentThread();
44        mRequestThreadOriginalClassLoader = mRequestThread.getContextClassLoader();
45        mMainThreadOriginalClassLoader = Looper.getMainLooper().getThread().getContextClassLoader();
46
47        ClassLoader newClassLoader = packageClass.getClassLoader();
48
49        Log.v(this, "Changing context classloader for thread %s from %s to %s",
50                mRequestThread.getName(),
51                mRequestThreadOriginalClassLoader,
52                newClassLoader);
53        mRequestThread.setContextClassLoader(newClassLoader);
54
55        Log.v(this, "Changing context classloader for MAIN thread from %s to %s",
56                mMainThreadOriginalClassLoader,
57                newClassLoader);
58        Looper.getMainLooper().getThread().setContextClassLoader(newClassLoader);
59
60        String dexCache = context.getCacheDir().toString();
61        Log.v(this, "Setting property %s to %s", DEXCACHE, dexCache);
62        System.setProperty(DEXCACHE, dexCache);
63    }
64
65    /**
66     * Restores the context classloader to the previous value.
67     */
68    public void tearDown() throws Exception {
69        Log.v(this, "Restoring context classloaders");
70        mRequestThread.setContextClassLoader(mRequestThreadOriginalClassLoader);
71        Log.v(this, "Clearing property %s", DEXCACHE);
72        System.clearProperty(DEXCACHE);
73    }
74}