我有一个服务,它从 SharedPreferences 中获取一些值,并根据它获取的值执行某些操作。问题是我总是到处得到 NullPointerException 因为我找不到上下文。我的测试代码是这样的。你能帮我吗?
public void setUp() throws Exception
{
super.setUp();
mam=getService();
}
public void testStart()
{
//Test 1
SharedPreferences pref = mam.getSharedPreferences("settings", mam.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt("hour", -1);
editor.putInt("minute", -1);
editor.commit();
mam.startService(new Intent()); //onCreate() or something else
boolean ok=mam.getOk();
assertFalse("T.38", ok);
}
我的服务是这样的:
public void onCreate()
{
pref = getApplicationContext().getSharedPreferences(
"settings", MODE_PRIVATE);
int h=pref.getInt("hour", -1);
int m=pref.getInt("minute", -1);
if(h!=-1 && m!=-1)
{
...
ok=true;
}
}
最佳答案
改变
mam.startService(new Intent());
到
Intent intent = new Intent(mam,ServiceClassName.class);
mam.startService(intent);
关于java - 服务测试中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19882307/