vendredi 20 mai 2016

Mockito mock method with comparing parameters - Misplaced argument matcher detected here

I'm trying to mock a method of EntityPersistor

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

I want to check if queryString matches a specific queryString and if params contains a specific value. If those two conditions are true, I want to return an specific object xy.

I'm new to mocking and mockito, but I tried to achieve this with two ArgumentMatcher inside the when() call.

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;
                }
            });

compiles successfull but won't run:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 

Misplaced argument matcher detected here:

how can I fix that? or is there a better way to mock a method and define a specific return case (if param 1 eq x and param 2 eq y)?

Aucun commentaire:

Enregistrer un commentaire