Mockito: checking overloaded methods with type arguments

Suppose you want mock to use an interface Mockitocontaining the following method signatures:

public void doThis(Object o);

public void doThis(Object... o)

I need to verify that doThis(Object o)(and not another method) was called exactly once.

At first, I thought the following line would do the trick:

verify(mock, times(1)).doThis(anyObject());

However, since this seems to work on Windows, it does not work on Linux because another method is expected to be called in this environment doThis.
This is because the argument appears to correspond to both method signatures , and one is chosen in a more or less unpredictable way. anyObject()

How can I guarantee that Mockito always choosesdoThis(Object o) to check?

+4
source share
2 answers

This is not a problem with mockito.

In the course of further research, I realized that the actual method was selected at compile time (JLS §15.12.2) . Thus, basically class files differed between windows and linux, which led to different mockito behaviors.

The interface is discouraged (see Effective Java, 2nd Edition, Item 42). I modified it to fit the following:

public void doThis(Object o);

public void doThis(Object firstObj, Object... others)

With this change, the expected (first) method will always be selected.

One more thing remains:
Why does the java compiler on windows (eclipse compiler) produce different output than the Oracle JDK javac on Linux?

ECJ, , java- .

+2

, : ?

ecj javac, JLS:

  • 1.7 , ( ) .
  • 1.8, (varargs)

-:

     7: invokestatic  #8                  // Method anyObject:()Ljava/lang/Object;
    10: checkcast     #9                  // class "[Ljava/lang/Object;"
    13: invokevirtual #10                 // Method doThis:([Ljava/lang/Object;)V

( )

: Java 8 anyObject() Object[]. checkcast, : (Object[])anyObject(). , doThis(Object...) varargs, Object[].

( " arity" ), .

, Java 7 -arity, , .

, JLS:

verify(mock, times(1)).doThis(Matchers.<Object>anyObject());

, doThis() Object - , :)

+2

Source: https://habr.com/ru/post/1619859/


All Articles