junit 组织,模拟,异常,误用,无效使用匹配器异常:

inkz8wg9  于 2023-02-23  发布在  其他
关注(0)|答案(2)|浏览(125)

我在服务和测试类中的方法:

public void updateSubModuleOrder(Long[] data, Long moduleSysId, Long userId) {
    try {
        for (int i = 0; i < data.length; i++) {
            SubModule subModule=new SubModule();

            int temp = i + 1;
            userSubmodule.setDsplySeq(temp);
            userSubModuleDao.saveOrUpdate(userSubmodule);
@Test
public void testupdateSubModuleOrder(){
    UserModuleServiceImpl userModuleServiceImpl = new UserModuleServiceImpl();
    UserSubModuleDao userSubModuleDao = mock(User//set the required param ,some code here//
    UserSubModuleId userSubModuleId=new UserSubModuleId();
    //some code//
    when(userSubModuleDao.findById((any(UserSubModuleId.class)),false)).thenReturn(userSubModule);
    when(userSubModuleDao.saveOrUpdate(any(UserSubModule.class))).thenReturn(null);
    userModuleServiceImpl.updateSubModuleOrder(data, moduleSysId, userId);

};*

我得到错误是

FAILED: testupdateSubModuleOrder
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.TestUserModuleServiceImpl.testupdateSubModuleOrder(TestUserModuleServiceImpl.java:267)

如果匹配器与原始值组合,则可能发生此异常:

//incorrect:
someMethod(anyObject(), "raw String");

使用匹配器时,所有参数都必须由匹配器提供。例如:

//correct:
someMethod(anyObject(), eq("String by matcher"));

方法findbyID是我的dao扩展的一个baseDao方法。它不是final或static,但我还是遇到了这个问题。

lvmkulzt

lvmkulzt1#

你要么指定 * no * matchers,要么指定 * all * 参数需要匹配。

when(userSubModuleDao.findById((any(UserSubModuleId.class)),false))

应为:

when(userSubModuleDao.findById(any(UserSubModuleId.class), eq(false)))

(我删除了any调用周围多余的括号。)
Matchers documentation

    • 警告:**

如果您使用参数匹配器,所有参数都必须由匹配器提供。

hc8w905p

hc8w905p2#

我的问题是我要模拟的目标方法是final方法。
错误消息显示

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

解决方案:
更改public final void foo() {}--〉public void foo() {}

相关问题