Mockito 3.4.0 Static Mocking Exception

Viewed 30292

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 { "" }}
}
5 Answers

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();
}

Try doing this way, you will not get this error. It worked for me.

try(MockedStatic mocked = mockStatic(SettingsUtility.class)) {
        mocked.when(SettingsUtility::method).thenReturn("whatever you want");
    }

Building on @Sudha 's answer. in Java you can use @BeforeClass and @AfterClass

private static MockedStatic<SettingsUtility> mockedSettings;

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

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

I tried below and worked for me.

MockedStatic mockedStatic = mockStatic(SettingsUtility.class)
mocked.when(SettingsUtility::method).thenReturn("any thing");
...........
//do all stuf

and at last close the mock

mockedStatic.close();

Mockito Inline works differently than the Mockito hence the failure. So what needs to be done is initialise and close the mocks explicitly.

You need to initialise the mockedStatic for your class

private MockedStatic<YourClassWithStaticMethod> mockedStatic;

Then add below code in BeforeEach and AfterEach

@BeforeEach
  public void init() {
    mockedStatic = mockStatic(YourClassWithStaticMethod.class);
  }

@AfterEach
  public void cleanup() {
    mockedStatic.close();
  }

And now you can set the mocked expectations.

mockedStatic.when(YourClassWithStaticMethod::staticMethodToMock).thenReturn(yourReturnedMockedObject);
Related