Android Unit Test giving an indescribable message to the Mockito stubbed method

I created the following test method, where I mock Settings.Secure and stub the getString method of this class.

@Test
public void testIsDevicePostOwner() throws Exception {
    String mockDeviceId = "2c3977ad-0867-49d6-aad8-c2762f373551";

    Post mockedPost = mock(Post.class);

    Settings.Secure mockedSecure = mock(Settings.Secure.class);

    ContentResolver mockContentResolver = mock(ContentResolver.class);

    when(mockedSecure.getString(mockContentResolver, Settings.Secure.ANDROID_ID)).thenReturn(mockDeviceId);
}

When I run the test, I get the following error:

java.lang.RuntimeException: Method getString in android.provider.Settings$Secure not mocked.

Does anyone have any ideas?

+4
source share
3 answers

Settings.Secure.getString- a static method, so mock(Settings.Secure.class)it will not be mocked. Even subclassing Settings.Secure and creating your own static getString will not help here.

I'm not sure if there is a magic of reflection that can help you in this case; no one comes to mind.

0
source

Try to add

testOptions {
    unitTests.returnDefaultValues = true
}

at build.gradle

http://tools.android.com/tech-docs/unit-testing-support

+1

If you want to mock the static method, use PowerMock

You will need to run PowerMockRunner and prepare the class for the test:

@PrepareForTest({Settings.Secure.class})

To taunt an object, you need to:

PowerMockito.mockStatic(Settings.Secure.class);

Then you can try:

when(Settings.Secure.getString(mockContentResolver, Settings.Secure.ANDROID_ID)).thenReturn(mockDeviceId);

Finally, you can check:

verifyStatic();
+1
source

Source: https://habr.com/ru/post/1584652/


All Articles