【发布时间】: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?
【问题讨论】:
-
@JaredBurrows 我看到你在 2016 年 8 月 28 日的提交 7ebf6a36911cc 中删除了这个测试。测试有问题吗?
-
你有提交的链接吗?
-
@JaredBurrows:当然:github.com/jaredsburrows/android-gradle-java-app-template/…
标签: android unit-testing