Search code examples
androidandroid-contextandroid-testingrobolectric

Why does Application.getContext() return null?


Hello I am implementing and SDK, and I need a context for some pieces of code, so, for get access to a context, I implemented this in a Application class:

public class SDKApp extends Application {

    private static SDKApp sdkContext;

    public static Context getContext() {
        return sdkContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sdkContext = this;

    }

}

For test this, I am using Robolectric, but the context is returning null value:

@RunWith(RobolectricTestRunner.class)
public class CallTest {

    private Context context = RuntimeEnvironment.application;

    @Test
    public void emailAuthenticationSuccessfulTest() {
        if (BuildConfig.FLAVOR.equals("dev")) {

            Context context = SDKApp.getContext();

            assertNotNull(context);
        }
    }
}

some idea about this?

Thanks


Solution

  • add you SDKApp Class into your manifest application tag like this

    <application
            android:name="SDKApp" // your complete package path to your SDKApp
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">