'How to mock DynamoDB with Mockito?

I got some code which already makes my DynamoDB instance mocked using PowerMockito like that:

@Mock
private DynamoDB dynamoDB;
 .....
PowerMockito.whenNew(DynamoDB.class).withAnyArguments().thenReturn(dynamoDB);

Our code coverage plugin doesn't like PowerMockito so he doesn't include these tests in the code coverage.

Due to that, now I need to use Mockito instead of PowerMockito.

I tried the following code below to make my DynamoDB mocked, but it failed:

DynamoDB mockedInstance = Mockito.mock(DynamoDB.class);
Mockito.doReturn(mockedInstance).when(carFactorySpy).carFactoryMethod("us-west-2");

The DynamoDB is being created like:

DynamoDB ddbCon = new DynamoDB(Regions.fromName(region));

or -

DynamoDB ddbCon = new DynamoDB(Regions.US_WEST_2);


Solution 1:[1]

Use Mockito.initMocks() or MockitoJUnitRunner annotation to setup mocking for your test. Also, it would be nice to provide with the failure message you are getting.

Solution 2:[2]

The details of your implementation are still a little unclear to me but here's a try.

If your test subject looks like...

private CarFactory carFactory;

public void foo() {
    DynamoDB ddbCon = carFactory.carFactoryMethod("us-west-2"));
    // use ddbCon
}

Then your unit test could look something like...

@Mock
private CarFactory carFactory;

@Test
public void fooShouldUseMockDynamoDb() {
    DynamoDb ddbCon = mock(DynamoDB.class);
    when(carFactory.carFactoryMethod("us-west-2")).thenReturn(ddbCon);
    // stub ddbCon
}

FWIW, I also try to avoid PowerMockito but more so because it is slow then code coverage not being captured.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 callmepills