Suppose I have two classes, MyObject1
and MyObject2
, both of which use Mockito to declare a static mock MyStaticObject
. Suppose MyObject1
forgets to close MyStaticObject
causing MyObject2
test cases to fail with the following exception:
org.mockito.exception.base.MockitoException:
For com.mypackage.MyStaticObject, static mocking is already registered in the current thread
public class MyObject1Test {
@Test
void testStaticMethodInMyObject1() {
// Improperly mocking static method without closing
MockedStatic<MyStaticObject> mockedStatic = Mockito.mockStatic(MyStaticObject.class);
mockedStatic.when(MyStaticObject::staticMethod).thenReturn("mocked value");
MyObject1 obj1 = new MyObject1();
assertEquals("mocked value", obj1.doSomething());
// Missing mockedStatic.close() here, which would have properly closed the static mock
}
}
public class MyObject2Test {
@Test
void testStaticMethodInMyObject2() {
// Attempt to mock the same static method
MockedStatic<MyStaticObject> mockedStatic = Mockito.mockStatic(MyStaticObject.class);
mockedStatic.when(MyStaticObject::staticMethod).thenReturn("another mocked value");
MyObject2 obj2 = new MyObject2();
assertEquals("another mocked value", obj2.doSomethingElse());
mockedStatic.close();
}
}
How can you determine MyStaticObject
is still registered to MyObject1
?