mark
mark

Reputation: 1809

dynamodb how do i mock mapper?

I have a section of dynamoDb related code that I want to test using mockito.

The method I want to test contains the following line:

List<NotificationFeedRecord> listResult = mapper.query(NotificationFeedRecord.class, queryExpression);

It's work fine when I test by hand, I submit a query and get the expected results back from dynamodb.

I'm writing unit tests and want to mock mapper.query.

I have:

mapper = mock(DynamoDBMapper.class);
List<NotificationFeedRecord> testList = new ArrayList<>();
when(mapper.query(any(), any())).thenReturn(testList);

Here I get an error

Error:(133, 37) java: no suitable method found for thenReturn(java.util.List<notificationfeed.lib.db.NotificationFeedRecord>)
      (argument mismatch; java.util.List<notificationfeed.lib.db.NotificationFeedRecord> cannot be converted to com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList<java.lang.Object>)

I've tried a range of fixes (e.g. Creating PaginatedQueryList and returning that, changing the query matchers), but all given an error.

The .query method is declared as follows:

public <T> PaginatedQueryList<T> query(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression) {
        return query(clazz, queryExpression, config);
    }

How does one mock mapper.query? Is there something special about it?

Upvotes: 3

Views: 15060

Answers (2)

mark
mark

Reputation: 1809

It was simple really, I had to mock the PaginatedQueryList and then:

when(mapper.query(any(), anyObject())).thenReturn(paginatedQueryList)

;

That worked for me.

These are all the conditions I set-up for our tests:

@Mock private PaginatedQueryList paginatedQueryList;
doReturn(mockQuery).when(utilSpy).getQueryExpression();

when(mockQuery.withFilterExpression(anyString())).thenReturn(mockQuery);
when(mockQuery.withLimit(anyInt())).thenReturn(mockQuery);
when(mockQuery.withExpressionAttributeValues(anyMap())).thenReturn(mockQuery);
when(mockQuery.withIndexName(anyString())).thenReturn(mockQuery);
when(mockQuery.withHashKeyValues(anyString())).thenReturn(mockQuery);
when(mockQuery.withConsistentRead(anyBoolean())).thenReturn(mockQuery); 
when(mockQuery.withRangeKeyCondition(anyString(), anyObject())).thenReturn(mockQuery);
when(mapper.query(any(), anyObject())).thenReturn(paginatedQueryList);

Upvotes: 5

Sean Morris
Sean Morris

Reputation: 135

I think you're just missing the correct matchers for the when() method. You can do something like this:

when(mapper.query(Matchers.anyListOf(NotificationFeedRecord.class), anyString()).thenReturn(testList);

Documentation for the anyListOf() matcher is here

Upvotes: 1

Related Questions