InvalidUseOfMatchersException when using mockito to force a CloneNotSupportedException in a Copy() method being junit tested

dead.frank :

I'm trying to access part of a copy method protected by a try catch using mockito while attempting to get 100% coverage in my junit tests. The class that contains the method I want to access implements cloneable making it difficult to throw ClassNotFoundExceptions.

I've tried to force this exception several different ways through mockito's ability to throw exceptions when calling a method but have always come up with an InvalidUseOfMatchersException.

following is the code i need to access and my best attempt at reaching it, respectively

catch(ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
}
MyClass dict = mock(MyClass.class);
Object obj1 = new Object();

when(MyClass.copy(anyObject())).thenThrow(ClassNotFoundException.class);
dict.copy(obj1);

I expect to reach the cnfe.printStackTrace() line but cannot.

Maxime Launois :

You seem to be mocking a static method, which is actually impossible. According to @Matthias, it would require modifying the class' byte code at runtime.

You must always call when with an instance method call because:

  1. This guarantees that the method will be called on the mock and not on the original class (i.e. MyClass).
  2. This prevents compile-time errors because such non-static methods cannot be referenced from a static context.

Here is the full Java code:

try {
    MyClass dict = mock(MyClass.class);
    Object obj1 = new Object();

    when(dict.copy(anyObject())).thenThrow(ClassNotFoundException.class);
    dict.copy(obj1);
} catch (ClassNotFoundException ex) {
    ex.printStackTrace();
}

This should output:

Exception in thread "main" java.lang.ClassNotFoundException

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=123906&siteId=1