Android 单元测试中的RecyclerView适配器

Android 单元测试中的RecyclerView适配器,android,unit-testing,Android,Unit Testing,在Android Studio中运行单元测试时如何测试支持库类? 根据介绍,它与默认的Android类一起工作: 单元测试在开发机器上的本地JVM上运行。我们的gradle插件将编译src/test/java中的源代码,并使用常用的gradle测试机制执行它。在运行时,将对修改后的android.jar版本执行测试,其中所有最终修改器都已剥离。这允许您使用流行的模拟库,如Mockito 但是,当我尝试在RecyclerView适配器上使用Mockito时,如下所示: @Before public

在Android Studio中运行单元测试时如何测试支持库类? 根据介绍,它与默认的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?

PowerMockito解决方案 步骤1: 从中找到正确的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: 设置单元测试类,准备目标类(包含最终方法):

步骤3: 替换Mockito。。。使用PowerMockito的方法:

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

编译器没有解释“when”键。您可以使用“Mockito.when”(在Java中)或Mockito.
when
(在kotlin中)。由于键“when”在Kotlin语言中已经存在,因此需要使用这些撇号。你可以使用where代替Mockito。
when
但是。

为什么要使用
PowerMockito
vs
Mockito
?主要是因为
hasStableIds()
声明为
final
。Mockito从2.1.0开始支持mocking final。检查我的测试:@JaredBurrows我看到你在2016年8月28日的commit 7ebf6911cc中删除了这个测试。测试有问题吗?你有提交的链接吗?@JaredBurrows:当然有:
adapter = PowerMockito.mock(PhotosHomeAlbumsAdapter.class);
PowerMockito.when(adapter.hasStableIds()).thenReturn(true);
@Before
public void setUp() throws Exception {
    adapter = mock(MyAdapterAdapter.class);
    when(adapter.hasStableIds()).thenReturn(true);
}