[英]Android Unit Test giving not mocked message for a Mockito stubbed method
I've created the following test method where I mock Settings.Secure and stub the getString method of that class. 我创建了以下测试方法,我在其中模拟Settings.Secure并存根该类的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);
}
When I run the test I get the following error: 当我运行测试时,我收到以下错误:
java.lang.RuntimeException: Method getString in android.provider.Settings$Secure not mocked.
Does anybody have any ideas? 有人有什么想法吗?
Try adding 尝试添加
testOptions {
unitTests.returnDefaultValues = true
}
in your build.gradle
在你的
build.gradle
More info here http://tools.android.com/tech-docs/unit-testing-support 更多信息,请访问http://tools.android.com/tech-docs/unit-testing-support
If you want to mock an static method, use PowerMock 如果要模拟静态方法,请使用PowerMock
You'll need to run with PowerMockRunner and Prepare the class for test: 您需要使用PowerMockRunner运行并准备测试类:
@PrepareForTest({Settings.Secure.class})
For mocking the object you need to: 要模拟对象,您需要:
PowerMockito.mockStatic(Settings.Secure.class);
Then you could try: 然后你可以尝试:
when(Settings.Secure.getString(mockContentResolver, Settings.Secure.ANDROID_ID)).thenReturn(mockDeviceId);
Finally, you could test: 最后,你可以测试一下:
verifyStatic();
Settings.Secure.getString
is a static method, so mock(Settings.Secure.class)
won't mock it. Settings.Secure.getString
是一个静态方法,因此mock(Settings.Secure.class)
不会模拟它。 Even subclassing Settings.Secure and creating your own static getString won't help here. 即使继承Settings.Secure并创建自己的静态getString也无济于事。
I'm not sure if there's any reflection magic that can help you out in this case; 我不确定在这种情况下是否有任何可以帮助你的反射魔法; none comes to mind.
没有人想到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.