Two tricks of mockito
stub java static method and mock scala object
As I write scala, I will add mockito-core to build.sbt as well as mockito-scala.
"org.mockito" % "mockito-core" % "5.2.0" % "test",
"org.mockito" %% "mockito-scala" % "1.17.14" % "test"
stub java static method
We could use mockStatic method to mock java static method. But mockStatic has not been added to mockito-scala, so we should use it as plain as it’s in java. For example:
// TheStaticClass is a java class with a static method staticMethod
val mockedStatic = mockStatic(classOf[TheStaticClass])
// stub the static method and return the instance we want.
// It could be a mocked instance or a real instance.
mockedStatic.when(() => StaticClass.staticMethod()).thenReturn(mockedInstance)
mock scala object
You should enable withObjectMocked feature to use it. It is mandatory to create the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
containing a single line:
mock-maker-inline
withObjectMocked[TheObject] { // a scoped mock object
// stub the object method here
when(TheObject.f).thenReturn(sth)
}