1 /*
2  * Copyright (C) 2018 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 
17 package com.android.car;
18 
19 import android.annotation.NonNull;
20 
21 import org.junit.runners.model.InitializationError;
22 import org.robolectric.RobolectricTestRunner;
23 import org.robolectric.annotation.Config;
24 import org.robolectric.manifest.AndroidManifest;
25 import org.robolectric.res.Fs;
26 import org.robolectric.res.ResourcePath;
27 
28 import java.net.MalformedURLException;
29 import java.net.URL;
30 import java.util.List;
31 
32 public class CarServiceRobolectricTestRunner extends RobolectricTestRunner {
CarServiceRobolectricTestRunner(Class<?> testClass)33     public CarServiceRobolectricTestRunner(Class<?> testClass) throws InitializationError {
34         super(testClass);
35     }
36 
37     /**
38      * We are going to create our own custom manifest so we can add multiple resource paths to it.
39      */
40     @Override
getAppManifest(Config config)41     protected AndroidManifest getAppManifest(Config config) {
42         try {
43             // Using the manifest file's relative path, we can figure out the application directory.
44             final URL appRoot =
45                     new URL("file:packages/services/Car/tests/robotests");
46             final URL manifestPath = new URL(appRoot, "AndroidManifest.xml");
47             final URL resDir = new URL(appRoot, "res");
48             final URL assetsDir = new URL(appRoot, "assets");
49 
50             return new AndroidManifest(Fs.fromURL(manifestPath), Fs.fromURL(resDir),
51                 Fs.fromURL(assetsDir), "com.android.car") {
52                 @Override
53                 public List<ResourcePath> getIncludedResourcePaths() {
54                     final List<ResourcePath> paths = super.getIncludedResourcePaths();
55                     return paths;
56                 }
57             };
58         } catch (MalformedURLException e) {
59             throw new RuntimeException("CarServiceRobolectricTestRunner failure", e);
60         }
61     }
62 
63     private static ResourcePath resourcePath(@NonNull String spec) {
64         try {
65             return new ResourcePath(null, Fs.fromURL(new URL(spec)), null);
66         } catch (MalformedURLException e) {
67             throw new RuntimeException("CarServiceRobolectricTestRunner failure", e);
68         }
69     }
70 }
71