Mockito - NullpointerException when stubbing Method

后端 未结 18 1623
半阙折子戏
半阙折子戏 2020-11-30 20:54

So I started writing tests for our Java-Spring-project.

What I use is JUnit and Mockito. It\'s said, that when I use the when()...thenReturn() option I can mock ser

18条回答
  •  执念已碎
    2020-11-30 21:07

    Another common gotcha is that the method signature is accidentally declared as 'final'.

    This one catches out a lot of people who work on codebases which are subjected to Checkstyle and have internalised the need to mark members as final.

    i.e. in the OP's example:

    object.method()

    Make sure that method() is not declared as final:

    public final Object method() {
    }
    

    Mockito cannot mock a final method and this will come up as a wrapped NPE:

    Suppressed: org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
    

    Buried deep in the error message is the following:

    Also, this error might show up because you use argument matchers with methods that cannot be mocked.
    Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
    Mocking methods declared on non-public parent classes is not supported.
    

提交回复
热议问题