TestUtil.java revision b381ee39223f4b835daac148d7e135d061860914
1package com.xtremelabs.robolectric.util;
2
3import com.xtremelabs.robolectric.RobolectricConfig;
4
5import java.io.File;
6import java.util.Collection;
7
8import static org.junit.Assert.assertTrue;
9
10public abstract class TestUtil {
11    public static File testDirLocation;
12
13    public static void assertEquals(Collection<?> expected, Collection<?> actual) {
14        org.junit.Assert.assertEquals(stringify(expected), stringify(actual));
15    }
16
17    public static String stringify(Collection<?> collection) {
18        StringBuilder buf = new StringBuilder();
19        for (Object o : collection) {
20            if (buf.length() > 0) buf.append("\n");
21            buf.append(o);
22        }
23        return buf.toString();
24    }
25
26    public static <T> void assertInstanceOf(Class<? extends T> expectedClass, T object) {
27        Class actualClass = object.getClass();
28        assertTrue(expectedClass + " should be assignable from " + actualClass,
29                expectedClass.isAssignableFrom(actualClass));
30    }
31
32    public static File file(String... pathParts) {
33        return file(new File("."), pathParts);
34    }
35
36    public static File file(File f, String... pathParts) {
37        for (String pathPart : pathParts) {
38            f = new File(f, pathPart);
39        }
40        return f;
41    }
42
43    public static File resourcesBaseDir() {
44        if (testDirLocation == null) {
45            File testDir = file("src", "test", "resources");
46            if (hasTestManifest(testDir)) return testDirLocation = testDir;
47
48            File roboTestDir = file("robolectric", "src", "test", "resources");
49            if (hasTestManifest(roboTestDir)) return testDirLocation = roboTestDir;
50
51            File roboSiblingTestDir = file(new File(new File(".").getAbsolutePath()).getParentFile().getParentFile(),"robolectric", "src", "test", "resources");
52            if (hasTestManifest(roboSiblingTestDir)) return testDirLocation = roboSiblingTestDir;
53
54
55            throw new RuntimeException("can't find your TestAndroidManifest.xml in "
56                    + testDir.getAbsolutePath() + " or " + roboTestDir.getAbsolutePath() + "\n or " + roboSiblingTestDir.getAbsolutePath());
57        } else {
58            return testDirLocation;
59        }
60    }
61
62    private static boolean hasTestManifest(File testDir) {
63        return new File(testDir, "TestAndroidManifest.xml").isFile();
64    }
65
66    public static File resourceFile(String... pathParts) {
67        return file(resourcesBaseDir(), pathParts);
68    }
69
70    public static RobolectricConfig newConfig(String androidManifestFile) {
71        return new RobolectricConfig(resourceFile(androidManifestFile), null, null);
72    }
73}
74