Mockito, what happens if I do not close my Mocked static method

Viewed 795
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
    MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)
    utilities.when(StaticUtils::name).thenReturn("Eugen");
    assertThat(StaticUtils.name()).isEqualTo("Eugen");
    utilities.close();
}

Why do I even need to close it?

2 Answers

As the javadoc states:

If this object is never closed, the static mock will remain active on the initiating thread

Since the class is actually implementing the AutoClosable interface, you can simply use the class in a try-with-resources - which is as recommend in the javadoc:

 assertEquals("foo", Foo.method());
 try (MockedStatic mocked = mockStatic(Foo.class)) {
 mocked.when(Foo::method).thenReturn("bar");
 assertEquals("bar", Foo.method());
 mocked.verify(Foo::method);
 }
 assertEquals("foo", Foo.method());
 

If you want the Mock to be active during all tests, you can simply never close the Mock. However, if you do so, I'd do it in an init-method and not in a test. If your tests however shall be independent and not show such behaviour, you need to close it.

In my case , when i didn't enclosed try inside try-with-resource, my subsequent TCs/Junits started failing, dont know what was the reason.

Related