Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Last active April 30, 2018 21:20
Show Gist options
  • Save patrickhammond/8b63295ff2035bb77101 to your computer and use it in GitHub Desktop.
Save patrickhammond/8b63295ff2035bb77101 to your computer and use it in GitHub Desktop.
Android Application class that is aware of if it is being created in the context of unit/instrumentation tests where the full application initialization is not desirable.
package com.myapp;
public class SampleApplication extends TestingAwareApplication {
@Override
protected String getFullyQualifiedTestFile() {
return "com.myapp.TestMode";
}
@Override
protected void initAppInstance() {
// Whatever you need to initialize...
}
}
package com.myapp;
import android.app.Application;
import android.util.Log;
import com.myapp.BuildConfig;
public abstract class TestingAwareApplication extends Application {
private static final String TAG = TestingAwareApplication.class.getSimpleName();
private boolean initialized = false;
@Override
public void onCreate() {
super.onCreate();
if (isTestExecution()) {
Log.e(TAG, "Starting without initializing the application for automated tests; call initAppInstanceIfNeeded() manually if needed.");
} else {
initAppInstanceIfNeeded();
}
}
private boolean isTestExecution() {
if (BuildConfig.DEBUG) {
try {
getClassLoader().loadClass(getFullyQualifiedTestFile());
return true;
} catch (Exception e) {
return false;
}
}
return false;
}
/**
* Return something from the androidTest source set.
* @return Example: "com.myapp.TestMode"
*/
protected abstract String getFullyQualifiedTestFile();
public void initAppInstanceIfNeeded() {
if (!initialized) {
initAppInstance();
initialized = true;
}
}
protected abstract void initAppInstance();
}
package com.myapp;
/**
* The main application class will try to load this class in via the classloader to determine if it
* is being run in the context of automated tests or not. It offers no other value to the test
* suite beyond changing the initialization behavior of the main application class.
*
* Ensure that this class lives in the androidTest source set!
*/
@SuppressWarnings("unused")
public class TestMode {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment