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:

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement