gpt4 book ai didi

java - 为什么我在模拟 TextView 时会收到 InvalidUseOfMatchersException?

转载 作者:行者123 更新时间:2023-12-01 11:08:44 25 4
gpt4 key购买 nike

我有一组测试来验证我们的 Android 应用程序中的某些功能。部分代码负责将某些字符串放入某些 TextView 中。所以我想创建模拟的 TextView 对象以在测试时使用:

public static TextView getMockTextView() {
TextView view = mock(TextView.class);
final MutableObject<CharSequence> text = new MutableObject<CharSequence>();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
text.value = (CharSequence) invocation.getArguments()[0];
return null;
}
}).when(view).setText((CharSequence) any());
when(view.getText()).thenReturn(text.value);
return view;
}

这适用于 2 参数 setText(CharSequence, BufferType) ...但是,我们的大部分代码只是调用 setText(CharSequence)所以我也想捕获这种情况下的字符串(正如您在上面的代码中看到的)。

但是我得到了这个异常:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.me.util.MockViewHelper.getMockTextView(MockViewHelper.java:49)

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

我已经尝试过( CharSequence)any()(CharSequence)anyObject() ,甚至 anyString()eq("") 只是为了看看它是否有效,Mockito 仍然不喜欢我试图告诉它在 1 参数中做什么setText() 的版本。

知道这里发生了什么吗?

最佳答案

来自the TextView docs :

public final void setText (CharSequence text)

Mockito can't mock final methods ; Mockito 生成的模拟/ spy 类实际上是一个代理,但由于 setText(CharSequence) 是最终的,JVM 假设它知道要调用哪个实现(TextView 的实际实现)并且不会咨询代理(Mockito 实现)作为虚拟方法调度将决定。大概 setText(CharSequence) 的实现实际上调用了 setText(CharSequence, BufferType) ,Mockito 假定这是您想要模拟的调用,因此它会给您错误消息“预期 2 名匹配者,记录 1 名”。 (第二个匹配器将用于 BufferType。)

您需要执行以下操作之一:

  • 使用Robolectric ,它使用特殊的类加载器将 Android 类替换为测试中可行的等效类。
  • 使用PowerMock ,它还使用一个特殊的类加载器来重写您的测试系统,即使在调用 final方法(以及许多其他附加功能)时也将委托(delegate)给模拟。
  • 完全跳过使用模拟,并使用真实对象或编写完全可模拟的包装层。

关于java - 为什么我在模拟 TextView 时会收到 InvalidUseOfMatchersException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com