本文介绍了使用Mockito模拟构建版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是使用Mockito模拟Build.Version.SDK_INT.已经尝试过:
My target is to mock Build.Version.SDK_INT with Mockito. Already tried:
final Build.VERSION buildVersion = Mockito.mock(Build.VERSION.class); doReturn(buildVersion.getClass()).when(buildVersion).getClass(); doReturn(16).when(buildVersion.SDK_INT);问题在于:在模拟之后需要方法时,而.SDK_INT不是方法.
Problem is that: when requires method after mock, and .SDK_INT is not a method.
推荐答案到目前为止,与该问题类似的其他问题似乎都需要使用反射.
So far from other questions similar to this one it looks like you have to use reflection.
在本地单元测试中Build.VERSION.SDK_INT的存根值
如何使用JUnit,EasyMock或PowerMock模拟静态最终变量
static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); }...然后在这种情况下像这样使用它...
...and then in this case use it like this...
setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 16);另一种解决方法是创建一个类,该类使用一种以后可以模拟的方法来访问/包装字段
Another way around would be to create a class that accesses/wraps the field in a method that can be later mocked
public interface BuildVersionAccessor { int getSDK_INT(); }然后模拟该类/接口
BuildVersionAccessor buildVersion = mock(BuildVersionAccessor.class); when(buildVersion.getSDK_INT()).thenReturn(16);更多推荐
使用Mockito模拟构建版本
发布评论