I'm trying to stub out a method call, e.g.
when(amazonDynamoDBClient.batchWriteItem(anyObject())).thenReturn(batchWriteItemResultMock);
I get this error
Error:(198, 34) java: reference to batchWriteItem is ambiguous
both method batchWriteItem(com.amazonaws.services.dynamodbv2.model.BatchWriteItemRequest) in com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient and method batchWriteItem(java.util.Map<java.lang.String,java.util.List<com.amazonaws.services.dynamodbv2.model.WriteRequest>>) in com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient match
I can't see how this is ambiguous - the method signatures are different, i.e.
public BatchWriteItemResult batchWriteItem(BatchWriteItemRequest request) {
and
public BatchWriteItemResult batchWriteItem(Map<String, List<WriteRequest>> requestItems) {
What am I doing wrong here?
This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used. Suppose we have a java program like below.
Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading.
Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.
As previously mentioned, since Mockito 3.4.0, we can use the Mockito.mockStatic (Class classToMock) method to mock invocations to static method calls. This method returns a MockedStatic object for our type, which is a scoped mock object.
Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when () and thenReturn () on the mock object. Sometimes we want to mock the behavior for any argument of the given type, in that case, we can use Mockito argument matchers.
But there’s a cleaner solution: Mockito provides an alternative stubbing API via the Mockito.doAnswer static method. If we use that API for the second stubbing (line 3) we’d avoid the exception: Why is this safe? By calling doAnswer first, we inform Mockito that we’re about to stub the next method call.
We usually mock the behavior using when () and thenReturn () on the mock object. Sometimes we want to mock the behavior for any argument of the given type, in that case, we can use Mockito argument matchers. Mockito argument methods are defined in org.mockito.ArgumentMatchers class as static methods.
You have two methods with the same name and return type, each with one parameter. So anyObject()
matches both of them. That's why you get the batchWriteItem is ambiguous
message.
You could use Mockito.any(Class<T> type)
and Mockito.anyMapOf(Class<K> keyClazz, Class<V> valueClazz)
to distinguish between them.
Docs for reference: any, anyMapOf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With