Sam
Sam

Reputation: 42427

NullPointerException when getting WindowManager from Service under Robolectric

I'm writing a test for a Service using Robolectric 2.4:

@RunWith(RobolectricTestRunner.class)
public class MyServiceTest {

    @Test
    public void someTest() {
        Robolectric.buildService(MyService.class)
            .create()
            .get()
            .getSystemService(Context.WINDOW_SERVICE);
    }

}

When getSystemService is called on the Service, a NullPointerException is thrown as shown below:

java.lang.NullPointerException
    at android.content.ContextWrapper.getSystemService(ContextWrapper.java:519)
    at MyServiceTest.someTest(MyServiceTest.java:10)

The problem doesn't happen when I call getSystemService on Robolectric.application or a Robolectric-made Activity; it seems to be a problem specific to services.

In the actual tests, my service is trying to get the WindowManager using itself as the Context, so I can't just use Robolectric.application to get it.

Upvotes: 1

Views: 1012

Answers (1)

David Boho
David Boho

Reputation: 2716

No Context, no ContextWrapper.

You have to attach a Context before your create a Service instance. So just call attach() before create().

So it will look like this:

@RunWith(RobolectricTestRunner.class)
public class MyServiceTest {

    @Test
    public void someTest() {
        Robolectric.buildService(UpdateService.class)
            .attach()
            .create()
            .get()
            .getSystemService(Context.WINDOW_SERVICE);
    }

}

Update for Robolectric >= 3.3 In Robolectric 3.3 attach is now deprecated and will be removed in 3.4 (see api doc). So since 3.3 you can drop the attach call (thanks to @inder).

@RunWith(RobolectricTestRunner.class)
public class MyServiceTest {

    @Test
    public void someTest() {
        Robolectric.buildService(UpdateService.class)
            .create()
            .get()
            .getSystemService(Context.WINDOW_SERVICE);
    }

}

Upvotes: 4

Related Questions