我创建了以下测试方法,我模拟了 Settings.Secure 并 stub 该类的 getString 方法。
@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);
}
当我运行测试时,出现以下错误:
java.lang.RuntimeException: Method getString in android.provider.Settings$Secure not mocked.
有没有人有什么想法?
最佳答案
如果你想模拟一个静态方法,使用PowerMock
您需要使用 PowerMockRunner 运行并准备类以进行测试:
@PrepareForTest({Settings.Secure.class})
为了模拟你需要的对象:
PowerMockito.mockStatic(Settings.Secure.class);
那你可以试试:
when(Settings.Secure.getString(mockContentResolver, Settings.Secure.ANDROID_ID)).thenReturn(mockDeviceId);
最后,你可以测试:
verifyStatic();
关于java - Android 单元测试未为 Mockito stub 方法提供模拟消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868207/