Reputation: 760
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 { "" }}
}
Upvotes: 64
Views: 84256
Reputation: 11
@sudha-chinnappa answer is the one. Use:
@AfterAll
public static void close() {
mockedSettings.close();
}
To close the static mocking
Upvotes: 0
Reputation: 231
Always use MockedStatic in function context inside try() that auto-closes it rather than using it as private static class variable. Using it at a class level variable will result into these sort of error even if you close them in AfterAll or AfterEach.
Example -
try ( MockedStatic mockedYourClassStatic = Mockito.mockStatic(YourClass.class) ) { ... }
Also you can refer to this -
Upvotes: 1
Reputation: 4799
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);
Upvotes: 13
Reputation: 275
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();
Upvotes: 2
Reputation: 1223
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();
}
Upvotes: 103
Reputation: 11786
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();
}
Upvotes: 19
Reputation: 417
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");
}
Upvotes: 33