Search code examples
javaunit-testingmockitomockstatic

Are those two ways of mocking static methods equal?


I'm using Java 17 with JUnit 5 and Mockito 5. I'm working on legacy code and adding some new tests or editing the old ones.

Normally when I mock static methods I do so as described on https://www.baeldung.com/mockito-mock-static-methods :

try(MockedStatic<MyClass> myClassMock = Mockito.mockStatic(MyClass.class)){
    myClassMock.when(MyClass::myMethod).thenReturn("myValue");
}

But I found some tests in the legacy Code where they used Mockito.when() instead of the static mock (in my case myClassMock)

So the same test code would look like:

try(MockedStatic<MyClass> myClassMock = Mockito.mockStatic(MyClass.class)){
    Mockito.when(MyClass::myMethod).thenReturn("myValue");
}

As far as I was able to observe, both variants seem to work.

So my question is: Is there any difference in behavior between those two variants?


Solution

  • In your case both will work. However,

    • myClassMock.when(MyClass::myMethod).thenReturn("myValue") - is the preferred approach as it is directly tied with MockedStatic<MyClass> & is scoped within the static mock context. It makes code more readable.
    • Mockito.when(MyClass::myMethod).thenReturn("myValue") is the general purpose method for stubbing regular mocks. In your case it is working for static mocks as well as myClassMock has been activated in the try block, but it might lead to confusion in large codebases as it’s less explicit about dealing with static mocks.