在Android中运行单元测试时,如何测试支持库类?根据对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?
发布于 2015-03-05 01:25:26
PowerMockito解
步骤1:从PowerMock中找到正确的Mockito & 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 {
第三步:替换莫奇托..。方法使用PowerMockito:
adapter = PowerMockito.mock(PhotosHomeAlbumsAdapter.class);
PowerMockito.when(adapter.hasStableIds()).thenReturn(true);
发布于 2020-12-29 02:50:18
@Before
public void setUp() throws Exception {
adapter = mock(MyAdapterAdapter.class);
when(adapter.hasStableIds()).thenReturn(true);
}
编译器没有解释"when“键。您可以使用"Mockito.when“(在Java中)或使用Mockito.when
(在kotlin中)。这些撇号是必要的,因为关键的“当”它已经存在于科特林语言。不过,您可以随时使用Mockito。when
。
https://stackoverflow.com/questions/28873840
复制