Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Unit Test: How to mock Android's context

I'm new to Android unit test and was wondering how I can mock the context if I want to unit test the getSomething() below.

Thanks a lot in advance!

public class Provider {
private final String packageName;
public Provider(Context context) {
     packageName = context.getPackageName();
}


public Data getSomething() {
    return get(packageName);
}

private Data get(String packageName) {
 // return something here based on the packageName

}

}

I tried

@Before
    public void setUp() throws Exception {
        provider = new Provider(mock(Context.class));
    }

    @Test
    public void DoSomethingTest() {
        final Data data = provider.getSomething();
        assertThat(data).isNotNull();
    }

But I got the error below: java.lang.RuntimeException: Stub! at android.content.Context.(Context.java:4) at android.content.ContextWrapper.(ContextWrapper.java:5)

like image 409
Green Ho Avatar asked Apr 13 '15 22:04

Green Ho


1 Answers

You call getPackageName(); on the Context-mock. To get this running you have to mock the method like:

Mockito.when(mock.getPackageName()).thenReturn("myPackage");

But this makes your test pretty much useless. But thinking about this, this isn't a test which I would write because (assuming it works as you expecting it) it just tests the framework method getPackageName(). In your tests you should test YOUR code or to be more specific your algorithms and not the successful call of methods.

like image 90
Kai Avatar answered Sep 22 '22 03:09

Kai