Show List

Mocking final classes and methods with Mockito

Mocking final classes and methods with Mockito can be challenging, since Mockito uses dynamic proxies to create mock objects, and dynamic proxies cannot be used to mock final classes or methods. However, Mockito provides an extension called Mockito-Inline that can be used to mock final classes and methods. Here's an example of how to use Mockito-Inline to mock a final method:

Suppose you have the following class with a final method that you want to mock:

java
Copy code
public class MyService { public final String getGreeting() { return "Hello, world!"; } }

To mock the getGreeting() method in a test, you can use Mockito-Inline to create a mock object for the MyService class. Here's an example of how to do this:

java
Copy code
@ExtendWith(MockitoExtension.class) public class MyServiceTest { @Test public void testGetGreeting() { MyService myService = mock(MyService.class, withSettings().defaultAnswer(CALLS_REAL_METHODS)); when(myService.getGreeting()).thenReturn("Hello, Mockito!"); String greeting = myService.getGreeting(); assertEquals("Hello, Mockito!", greeting); } }

In this example, we use the MockitoExtension JUnit 5 extension to enable Mockito-Inline in the test. We then create a mock object for the MyService class using the mock() method provided by Mockito, passing in the class that we want to mock. We also use the withSettings() method to specify the default answer for the mock object, which in this case is to call the real method (CALLS_REAL_METHODS). Finally, we use the when() method to specify the return value for the getGreeting() method, as we did in previous examples.

By using Mockito-Inline and the withSettings() method to mock final classes and methods, we can create mock objects for classes and methods that would otherwise be difficult or impossible to mock using standard Mockito functionality. It's worth noting that using Mockito-Inline can have some performance implications, since it uses bytecode manipulation to modify the final class or method. It's also important to exercise caution when using Mockito-Inline, since it can potentially create brittle tests that depend on implementation details.


    Leave a Comment


  • captcha text