如何在
Android Studio中运行单元测试时测试支持库类?
根据
http://tools.android.com/tech-docs/unit-testing-support的介绍,它适用于默认的Android类:
Unit tests run on a local JVM on your development machine. Our gradle plugin will compile source code found in src/test/java and execute it using the usual Gradle testing mechanisms. At runtime, tests will be executed against a modified version of android.jar where all final modifiers have been stripped off. This lets you use popular mocking libraries, like 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&从https://code.google.com/p/powermock/wiki/MockitoUsage13开始的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);