【问题标题】:NullPointerException getting application context when running unit testNullPointerException 在运行单元测试时获取应用程序上下文
【发布时间】:2015-05-18 12:05:21
【问题描述】:

我有一个自定义应用程序类,MyApplication(扩展应用程序)。我有一个 getInstance() 方法,它只返回自己,这样我就可以从任何地方访问应用程序上下文。

我正在尝试对调用 MyApplication.getInstance() 的方法进行单元测试,但它返回 null,因此我的单元测试失败。

有人知道怎么做吗?还是只需要将我的应用程序上下文传递到要测试的方法中,以便对该方法运行测试。

这里有一些代码:

我的应用程序:

public class MyApplication extends Application
{
    private static MyApplication sInstance;

    public static MyApplication getInstance()
    {
        return sInstance;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        sInstance = this;
    }
}

测试方法:

public static String getErrorMessage(int httpStatus)
{
    // GETTING NULL POINTER EXCEPTION ON THIS LINE
    Resources resources = Bakery.getInstance().getApplicationContext().getResources();
    // ...
}

单元测试类:

public class ManagerApiTest extends AndroidTestCase
{

    public void testGetErrorMessage() throws Exception
    {
        Resources resources = getContext().getResources();

        String messageInternal = ManagerAPI.getErrorMessage(500);
        assertEquals(resources.getString(R.string.server_error_internal), messageInternal);
    }
}

【问题讨论】:

  • 你还没有实例化私有静态 Bakery sInstance; public static Bakery getInstance() { return sInstance; },因此调用 get 方法将返回 null。你需要模拟它。
  • 感谢@Stultuske,sInstance 在 onCreate() 中被实例化。
  • 是的,但我没有看到对 onCreate() 的实际调用
  • onCreate() 在应用创建时被系统调用。

标签: java android unit-testing android-testing android-context


【解决方案1】:

尝试改变

public static Bakery getInstance()
{
    return sInstance;
}

进入

public static Bakery getInstance()
{
    if(sInstance != null) {
      return sInstance;
    } else {
       return new Bakery();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多