当前位置: 首页 > 知识库问答 >
问题:

具有比较参数的Mockito模拟方法-此处检测到错误位置的参数匹配器

夹谷志
2023-03-14

我试图模拟EntityPersistor的一个方法

T getSingleResultFromTypedQuery(String queryString, Map<String, Object> params);

我想检查queryString是否匹配特定的queryString,以及params是否包含特定的值。如果那两个条件为真,我想返回一个特定的对象XY。

EntityPersistor<UserEntity> entityPersistorMocked = mock(EntityPersistorStub.class);

when(entityPersistorMocked.getSingleResultFromTypedQuery(argThat(new ArgumentMatcher<String>() {
        @Override
        public boolean matches(Object o) {
            return "SELECT u FROM UserEntity u where u.username = :u".equals(o.toString());
        }
    }), argThat(new ArgumentMatcher<Map<String, Object>>() {
        @Override
        public boolean matches(Object o) {
            HashMap<String, Object> params = (HashMap<String, Object>) o;
            if (params.containsKey('u') && params.get('u').toString().equals("hans")) {
                return true;
            } else {
                return false;
            }
        }
    })))
            .thenAnswer(new Answer<UserEntity>() {
                @Override
                public UserEntity answer(InvocationOnMock invocation) throws Throwable {
                    UserEntity user = new UserEntity();
                    user.setUserId(1);
                    user.setDisplayName("Dummy User");
                    user.setUsername("hans");
                    user.setPassword("pass");
                    return user;
                }
            });
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 

在此处检测到错误的参数匹配器:

我该怎么解决呢?或者是否有更好的方法来模拟一个方法并定义一个特定的返回大小写(如果param1 eq x和param2 eq y)?

共有1个答案

戚翰飞
2023-03-14

我只想说:

Answer<UserEntity> answer = new Answer<UserEntity>() {
   public UserEntity answer(InvocationOnMock invocation) throws Throwable {
       String queryString = (String) invocation.getArgument(0);
       Map params = (Map) invocation.getArgument(1);
       if ("foo".equals(queryString) && params.containsKey("bar")) {
          return x;
       } else {
          return y;
       }
   }
};
when(mock.getSingleResultFromTypedQuery(anyString(), any(Map.class)).thenAnswer(answer);
 类似资料: