RecyclerView适配器在单元测试中



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

单元测试在开发机器上的本地JVM上运行。我们的gradle插件将编译src/test/java中的源代码,并使用常用的gradle测试机制执行它。在运行时,测试将针对android.jar的修改版本执行,在该版本中,所有最终修饰符都已被剥离。这允许您使用流行的mocking库,如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版本来自https://code.google.com/p/powermock/wiki/MockitoUsage13,将其添加到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:替换Mockito。。。PowerMockito的方法:

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);
}

编译器没有解释";当";钥匙您可以使用";Mockito;(在Java中)或Mockito。when(在kotlin)。这些撇号是需要的,因为键";当";它已经存在于科特林语中。您可以使用"每当"代替Mockito。when

相关内容

最新更新