【问题标题】:RecyclerView Adapter in unit test单元测试中的 RecyclerView 适配器
【发布时间】:2015-03-05 09:07:33
【问题描述】:

在 Android Studio 中运行单元测试时如何测试支持库类? 根据http://tools.android.com/tech-docs/unit-testing-support 的介绍,它适用于默认的 Android 类:

单元测试在您的开发机器上的本地 JVM 上运行。我们的 gradle 插件将编译 src/test/java 中的源代码并使用通常的 Gradle 测试机制执行它。在运行时,将针对 android.jar 的修改版本执行测试,其中所有最终修饰符都已被剥离。这让您可以使用流行的模拟库,例如 Mockito。

但是,当我尝试像这样在 RecyclerView 适配器上使用 Mockito 时:

@Before
public void setUp() throws Exception {
    adapter = mock(MyAdapterAdapter.class);
    when(adapter.hasStableIds()).thenReturn(true);
}

然后我会收到错误信息:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
   It is a limitation of the mock engine.

原因是支持库没有提供这样一个“所有最终修饰符都被剥离”的jar文件。

那你怎么测试呢?通过子类化和覆盖最终方法(这不起作用,不)。也许是 PowerMock?

【问题讨论】:

标签: android unit-testing


【解决方案1】:

PowerMockito 解决方案

第 1 步: 从https://code.google.com/p/powermock/wiki/MockitoUsage13 中找到正确的 Mockito 和 PowerMock 版本,将其添加到 build.gradle:

testCompile 'org.powermock:powermock-module-junit4:1.6.1'
testCompile 'org.powermock:powermock-api-mockito:1.6.1'
testCompile "org.mockito:mockito-core:1.10.8"

仅根据使用页面一起更新它们。

第 2 步: 设置单元测试类,准备目标类(包含最终方法):

@RunWith(PowerMockRunner.class)
@PrepareForTest( { MyAdapterAdapter.class })
public class AdapterTrackerTest {

第 3 步: 用 PowerMockito 替换 Mockito... 方法:

adapter = PowerMockito.mock(PhotosHomeAlbumsAdapter.class);
PowerMockito.when(adapter.hasStableIds()).thenReturn(true);

【讨论】:

  • 为什么使用PowerMockito 和Mockito?
  • 主要是因为hasStableIds() 被声明为final。
  • Mockito 从 2.1.0 开始支持模拟决赛
【解决方案2】:
@Before
public void setUp() throws Exception {
    adapter = mock(MyAdapterAdapter.class);
    when(adapter.hasStableIds()).thenReturn(true);
}

编译器没有解释“when”键。您可以使用“Mockito.when”(在 Java 中)或 Mockito.when(在 kotlin 中)。这些撇号是必需的,因为它在 Kotlin 语言中已经存在的关键“何时”。不过,您可以随时使用 Mockito.when。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多