Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito 3.4.0 Static Mocking Exception

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 { "" }}
}
like image 591
Qumber Abbas Avatar asked Aug 05 '20 10:08

Qumber Abbas


People also ask

Can we mock static methods in Mockito?

Since static method belongs to the class, there is no way in Mockito to mock static methods.

How do I reset my static mock?

Try moving your static mock setup to an @BeforeClass setup method, but leave your reset(mocks) call in your test setup() method. You want to setup your mockStatic only once, but because they're static, you will want to reset them for every test or they'll muddle with subsequent tests.

How do you mock a private static method?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


2 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();
}
like image 144
Sudha Chinnappa Avatar answered Sep 17 '22 16:09

Sudha Chinnappa


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");
    }
like image 44
Rajesh Kumar Avatar answered Sep 17 '22 16:09

Rajesh Kumar