-3
我有一个自定义应用程序类MyApplication(扩展应用程序)。我有一个getInstance()方法,它只是返回自己,这样我就可以从任何地方访问应用程序上下文。NullPointerException运行单元测试时获取应用程序上下文
我想单元测试调用MyApplication.getInstance()的方法,但它返回null,所以我的单元测试失败。
有谁知道如何做到这一点?或者,我需要将我的应用程序上下文传递给要测试的方法,以便对该方法运行测试。
下面是一些代码:
所有MyApplication:
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);
}
}
您还没有实例化的私有静态面包店sInstance; public static Bakery getInstance() { return sInstance; },所以调用get方法将返回null。你需要嘲笑它。 – Stultuske
谢谢@Stultuske,sInstance在onCreate()中实例化。 –
是的,但我没有看到onCreate() – Stultuske