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,