我正在尝试使用 Mockito 运行单元测试,但我有一个辅助方法,我想在其中使用真正的类:
public static Location fromCoordinates(float latitude, float longitude){
Location result = new Location("");
result.setLatitude(latitude);
result.setLongitude(longitude);
return result;
}
上述方法当前会导致“方法...未模拟”。错误描述here ,它给出了如何使用默认值的建议,但这对我来说不起作用,因为这会导致纬度和经度随后返回 0。
我还尝试在测试开始时添加 Mockito.mock(Location.class, CALLS_REAL_METHODS);
,但似乎没有效果。
如何配置我的测试以使用真实的 Location 类,同时仍然使用mockito 来模拟其他类?
[编辑] 对于上下文,这是有问题的单元测试
@Test
public void OpensCenteredInLocation() {
Location l = Mockito.mock(Location.class, CALLS_REAL_METHODS);
//When the user starts the app
LocationManager m = Mockito.mock(LocationManager.class);
Location initial = LocationHelper.fromCoordinates(10, 15); //<--it fails here
doReturn(initial).when(m).getLastKnownLocation(any(String.class));
MyApp main = new MyApp(m);
//Then it should open with the map centered in the user's location
Assert.assertEquals(10, main.CameraPosition.longitude, 0);
Assert.assertEquals(15, main.CameraPosition.longitude, 0);
}
当失败时,它会抛出java.lang.RuntimeException: Method setLatitude in android.location.Location not mocked。有关详细信息,请参阅http://g.co/androidstudio/not-mocked。
最佳答案
我认为真正的问题不是因为 fromCooperatives
方法是静态的,在我看来真正的问题是因为 Location
是一个内置的 Android 类。
事实上,当您运行单元测试时,它是在您的计算机上运行,而不是在 Android 设备上运行。所以你不能使用内置的Android类。
然后根据这个doc告诉您可以添加到 build.gradle 文件
android {
...
testOptions {
unitTests.returnDefaultValues = true
}
}
这可以防止 android 类在您尝试使用它们时抛出异常,但请注意,这样做的目的是
更改行为,以便方法返回 null 或零
关于java - 如何同时使用真实类和mockito?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554003/