获取上下文的静态方法不起作用

时间:2019-07-10 13:57:00

标签: android android-manifest android-context robolectric android-application-class

您好,我正在开发一个模块,为此需要获取静态方法的上下文,我有以下代码:

JUnit:

@RunWith(RobolectricTestRunner.class)
public class AApplicationTest {
    @Test
    public void hasAContextTest() {
        Context context = AApplication.getAppContext();
        assertNotNull(context);
    }
}

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="apps.com.a">

    <application android:name=".AApplication"
        tools:replace="android:name"/>

</manifest>

应用

public class AApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        AApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return AApplication.context;
    }

}

问题是assertNotNull(context)失败,因为上下文为空。

我获得了有关如何通过静态方式here获取上下文的信息,但不知道为什么会这样吗?

此应用程序中有两个模块,所有模块和应用程序都具有这种模式。

谢谢

0 个答案:

没有答案