Skip to content
Advertisement

How to mock static method calls from multiple classes in a single try block using Mockito?

I want to mock static methods from two different classes. Right now, my code is like this:

try(MockedStatic<ObjectFactory> objectFactory = mockStatic(ObjectFactory.class)){
    objectFactory.when(() -> ObjectFactory.getObject(Provider.class)).thenReturn(new Provider());
    .....
}

I want to mock another static method call from Context.class. Is there a way to define a MockedStatic object of context in the same try block, without using a nested try block.

Without using try block I think we can use something like this

MockedStatic<ObjectFactory> objectFactory = mockStatic(ObjectFactory.class);
MockedStatic<Context> contextMock = mockStatic(Context.class);
......
objectFactory.close();
contextMock.close();

but if the test throws exception, the mocks will not be closed and other tests that use the mock will throw an exception.

Advertisement

Answer

The try-with-resources statement can define multiple AutoCloseable instances, both of which will be closed at the end:

try (MockedStatic<ObjectFactory> objectFactory = mockStatic(ObjectFactory.class);
     MockedStatic<Context> contextMock = mockStatic(Context.class)) {
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement