Reputation: 901
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)
Upvotes: 6
Views: 8482
Reputation: 39632
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.
Upvotes: 2