我想模拟PermissionHostCompat类的操作requestPermission(@NonNull String permission, int requestCode)
。
public class PermissionHostCompat {
(...)
public void requestPermission(@NonNull String permission, int requestCode) {
requestPermissions(new String[]{permission}, requestCode);
}
public void requestPermissions(@NonNull String[] permissions, int requestCode) {
if (activity != null) {
ActivityCompat.requestPermissions(activity, permissions, requestCode);
} else if (fragment != null) {
FragmentCompat.requestPermissions(fragment, permissions, requestCode);
} else {
fragmentv4.requestPermissions(permissions, requestCode);
}
}
(...)
}
我是这样做的:
@Mock
PermissionHostCompat permissionHostCompat;
//...
Answer<Void> requestPermissionAction = new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
// some code
return null;
}
};
doAnswer(requestPermissionAction).when(permissionHostCompat)
.requestPermission(anyString(), anyInt());
它给我带来了一个错误:
org.mockito.exceptions.missing.InvalidUseOfMatchersException:
参数匹配器的使用无效!
预计有0个匹配者,记录了2个:如果匹配器与原始值组合,则可能会发生此异常:
//不正确:
someMethod(anyObject(),"原始字符串");
使用匹配器时,所有参数都必须由匹配器提供。
例如:
//更正:
someMethod(anyObject(),eq("匹配器字符串");
我不知道为什么。我还尝试了any(String.class)
、any(int.class)
和所有选项之间的组合。
我的进口:
导入静态组织.mockito.Matchers.any;
导入静态org.mockito.Matchers.anyInt;
导入静态org.mockito.Matchers.anyString;
导入staticcorg.mockito.mockito.doAnswer;
导入静态org.mockito.mockito.when;
Mockito版本:1.10.19
我做错了什么?
试试它是否能与Mockito 2一起使用。但进口应该改变:
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Matchers.anyString;