Is It Possible To Find Out If An Android Application Runs As Part Of An Instrumentation Test
Solution 1:
A much simpler solution is check for a class that would only be present in a test classpath, works with JUnit 4 (unlike the solution using ActivityUnitTestCase) and doesn't require to send custom intents to your Activities / Services (which might not even be possible in some cases)
privatebooleanisTesting() {
try {
Class.forName("com.company.SomeTestClass");
returntrue;
} catch (ClassNotFoundException e) {
returnfalse;
}
}
Solution 2:
Since API Level 11, the ActivityManager.isRunningInTestHarness() method is available. This might do what you want.
Solution 3:
If you are using Robolectric, you can do something like this:
publicbooleanisUnitTest() {
String device = Build.DEVICE;
String product = Build.PRODUCT;
if (device == null) {
device = "";
}
if (product == null) {
product = "";
}
return device.equals("robolectric") && product.equals("robolectric");
}
Solution 4:
If you're using ActivityUnitTestCase, you could set a custom Application object with setApplication, and have a flag in there to switch database sync on or off? There's an example of using a custom Application object on my blog:
http://www.paulbutcher.com/2011/03/mock-objects-on-android-with-borachio-part-3/
Solution 5:
You can pass an intent extra to your activity indicating it's under test.
1) In your test, pass "testMode" extra to your activity:
publicvoidsetUp()throws Exception {
super.setUp();
IntentactivityIntent=newIntent();
activityIntent.putExtra("testMode", true);
setActivityIntent(activityIntent);
}
2) In your activity, check for testMode:
Bundleextras= getIntent().getExtras();
if (extras != null && extras.getBoolean("testMode")) {
// disable your database sync
}
Post a Comment for "Is It Possible To Find Out If An Android Application Runs As Part Of An Instrumentation Test"