Skip to content

Instantly share code, notes, and snippets.

@hosokawa0825
Created February 27, 2015 03:07
Show Gist options
  • Save hosokawa0825/97f507c6fa688657c446 to your computer and use it in GitHub Desktop.
Save hosokawa0825/97f507c6fa688657c446 to your computer and use it in GitHub Desktop.
public class MyTestRunner extends RobolectricTestRunner {
public MyTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
@Override
protected AndroidManifest getAppManifest(Config config) {
System.setProperty("android.assets", "./src/test/assets");
return super.getAppManifest(config);
}
@Override
protected ResourceLoader createAppResourceLoader(final ResourceLoader systemResourceLoader, final AndroidManifest appManifest) {
try {
RoutingResourceLoader loader = (RoutingResourceLoader) super.createAppResourceLoader(systemResourceLoader, appManifest);
Map<String, ResourceLoader> resourceLoaders = (Map<String, ResourceLoader>) Whitebox.getInternalState(loader, "resourceLoaders");
OverlayResourceLoader overlayResourceLoader = (OverlayResourceLoader) resourceLoaders.get(appManifest.getPackageName());
List<PackageResourceLoader> packageResourceLoaders = (List<PackageResourceLoader>) Whitebox.getInternalState(overlayResourceLoader, "subResourceLoaders");
ResourcePath rpInjected = new ResourcePath(appManifest.getRClass(), appManifest.getPackageName(), Fs.fileFromPath("../app/src/main/res"), Fs.fileFromPath("../app/src/main/assets"));
packageResourceLoaders.add(createResourceLoader(rpInjected));
rpInjected = new ResourcePath(appManifest.getRClass(), appManifest.getPackageName(), Fs.fileFromPath("../app/src/test/res"), Fs.fileFromPath("../app/src/test/assets"));
packageResourceLoaders.add(createResourceLoader(rpInjected));
return loader;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected Class<? extends TestLifecycle> getTestLifecycleClass() {
return MyTestLifecycle.class;
}
public static class MyTestLifecycle extends DefaultTestLifecycle {
private static boolean setUpIsDone = false;
public MyTestLifecycle() throws Exception {
super();
if (!setUpIsDone) {
// この処理を呼ぶタイミングとしては一見beforeTestの方が適切に見えるが、
// beforeTestメソッドが呼ばれる前にBuild.VERSION.RELEASE等にShadowSystemPropertiesから
// 取得した文字列がセットされるためbeforeTestでは遅い。そのためここで呼んでいる。
setUpBeforeAllTestCases();
setUpIsDone = true;
}
}
/** テスト実行前に一度だけ実行する処理 */
private void setUpBeforeAllTestCases() throws Exception {
ShadowLog.stream = System.out;
// OSのバージョン、端末のモデル番号をShadowSystemPropertiesから取得できるようにする
Field field = ShadowSystemProperties.class.getDeclaredField("VALUES");
field.setAccessible(true);
Map<String, Object> values = (Map<String, Object>) field.get(null);
values.put("ro.build.version.release", "5.0.0");
values.put("ro.product.model", "Nexus 7");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment