Testing with SugarORM and Robolectric

↘锁芯ラ 提交于 2019-12-01 09:24:59

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!