Mockito 3.4.0 Static Mocking Exception

Qumber Abbas picture Qumber Abbas · Aug 5, 2020 · Viewed 18.2k times · Source

I am getting the following exception when trying to mock the static method.

For SettingsUtility, static mocking is already registered in the current thread To create a new mock, the existing static mock registration must be deregistered

@Before
fun setUp() {
    mockStatic(SettingsUtility::class.java) {
        `when` { SettingsUtility.method(app) }.thenReturn { "" }}
}

Answer

Sudha Chinnappa picture Sudha Chinnappa · Aug 7, 2020

The returned object's MockedStatic.close() method must be called upon completing the test or the mock will remain active on the current thread.

I am not sure if it is the same as how its done in Java. Hope this Java code snippet helps

private static MockedStatic<SettingsUtility> mockedSettings;

@BeforeAll
public static void init() {
    mockedSettings = mockStatic(SettingsUtility.class);
}

@AfterAll
public static void close() {
    mockedSettings.close();
}