使用Mockito模拟构建版本

编程入门 行业动态 更新时间:2024-10-26 16:21:56
本文介绍了使用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模拟构建版本

本文发布于:2023-10-31 07:12:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545394.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:版本   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!