mockito: How to match varargs in java 8? -
i'm working on migrating project java 7 8, , have gotten compilation error in mockito "when" case i'm having hard time tracking down:
when(queryrunner.query(any(string.class), any(resultsethandler.class), anyvararg())).thenreturn(mockedwordresultlist);
gives me compilation error of:
java: reference query ambiguous both method <t>query(java.lang.string,java.lang.object,org.apache.commons.dbutils.resultsethandler<t>) in org.apache.commons.dbutils.queryrunner , method <t>query(java.lang.string,org.apache.commons.dbutils.resultsethandler<t>,java.lang.object...) in org.apache.commons.dbutils.queryrunner match
this error happens in build 1.8.0-b128, doesn't happen in 1.7.0_45. i'm using mockito 1.9.5.
what's correct way use anyvararg()
argument matching in java 8?
the problem type inference has been improved. anyvararg()
generic method using in nested method invocation. before java 8 limitations of type inference forced treating method <t> t anyvararg()
<object> object anyvararg()
when placed argument method invocation without inserting explicit type arguments.
so query(string, resultsethandler, object...)
matched third argument treated being of type object
.
but java 8 type inference works nested method calls. since <t> t anyvararg()
type parameter <t>
can anything, can resultsethandler
well. query(string,object,resultsethandler)
match candidate now.
(i omitted type parameter <t>
outer call in both cases make less confusing)
since have 2 possible matches now, normal procedure of method selection applies here. , yes, it’s ambiguous. first parameter same, string
, other 2 resultsethandler
more specific object
while 1 candidate accepts more specific type second parameter, other third (and follow-ups).
it’s clear type parameters allow method’s return type source of ambiguity apis mockito’s containing such methods corner case of java programming. have force type either generic way matchers.<desired>anyvararg()
or via type cast (desired)anyvararg()
.
Comments
Post a Comment