Stubbing final methods with PowerMock

In this recipe, we will stub a final method and verify the object under test's behavior using JUnit. Since Mockito can't stub final methods, we'll use PowerMock to do it.

As usual, when dealing with PowerMock, you have to be really sure of what you are doing. You shouldn't need to use it with well-written code. Just follow the SOLID principles (see Chapter 2, Creating Mocks, for more information) and you shouldn't have the need to use this library.

PowerMock can be useful when dealing with legacy code or stubbing third-party libraries (you can check Chapter 8, Refactoring with Mockito, to see how to use PowerMock to refactor legacy code).

Getting ready

To use PowerMock, you have to add it to your classpath. Check ...

Get Mockito Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.