As As
As As

Reputation: 2107

NullPointerException in a service test

I have a service that takes some values from SharedPreferences and do something based on the value it took. The problem is that i always get NullPointerException everywhere because i can't find a context. My test code is this. Can you help me?

    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);
    }

My service is this:

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;
    }
}

Upvotes: 0

Views: 58

Answers (1)

Gopal Gopi
Gopal Gopi

Reputation: 11131

change

mam.startService(new Intent());

to

Intent intent = new Intent(mam,ServiceClassName.class);
mam.startService(intent);

Upvotes: 1

Related Questions