I trying to setup an testing environment for my android project. The basic Robolectric setup is done. I used this nice tutorial. If I comment out SugarORM in my Manifest.xml
Ok try next. Add next class to you test code:
public class TestSugarApp
extends SugarApp
{
@Override
public void onCreate() {}
@Override
public void onTerminate() {}
}
The class named Test will be loaded and used by Robolectric and you can override some things that are not relevant for testing. I'm trying to prevent to execute code from SugarApp
in onCreate
and onTerminate
(https://github.com/satyan/sugar/blob/master/library/src/com/orm/SugarApp.java).
@Eugen Martynov's answer works perfectly (thanks alot!). However, when you've extended android.app.Application yourself (which on its turn extends SugarApp), then you'll also exclude your own code.
I've solved this with using this code:
The Application class in the test code (as opposed to Eugen's answer):
public class TestApp extends App {
/** Prevents onCreate() and onTerminate() to call their super (in which {@link com.orm.SugarApp} is initialized) */
@Override
protected boolean callSuper() {
return false;
}
}
My own Application class (extending SugarApp):
public class App extends com.orm.SugarApp {
private static Context context;
public static Context getContext() {
return context;
}
@Override
public void onCreate() {
if (callSuper()) {
super.onCreate();
}
// My own code is always executed, also during unittests
context = getApplicationContext();
}
@Override
public void onTerminate() {
if (callSuper()) {
super.onTerminate();
}
}
protected boolean callSuper() {
return true; // Super is executed by default
}
}
I agree it doesn't look very beautiful (any advice to make this better?), but it works perfectly for me!
ps. I declared my application class in my manifest like this:
<application
android:name=".App"