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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With