Today, I will demostrate how we can mock final class and final methods using PowerMocks (Mockito api) - Mocks on steroids!
I am going to take a ficticious example, were AnotherService class's invokeFinal() method invokes a final method on the instance of FinalService class which is a final class.
Code under test:
The final method doSomething in the final Class FinalService does nothing, just throws an exception. AnotherService's invokeFinalMethod invokes doSomething method.
Most common mocking framework in the java world cannot mock final classes/methods because they are typically based on creating proxies. Creating proxies for final classes is not possible as we cannot subclass a final classes.
So how we do we it in PowerMocks (Mockito api)?
How will we test it - How do they do it!:
Aha! Its tad simple. We don't need to do anything special here.
We have to use @PrepareForTest annotation with FinalService so that PowerMocks can actually mock FinalService (Go Here for explanation on @PrepareForTest). Next up, we need to create the stub of FinalService using the following code
Then, we have two approaches
- We can either stub doSomething method and assert that the return value is what we expect (State based testing)
- We can verify that the doSomething method was actually invoked (Interaction based testing)
State based testing:
Interaction based testing:
It is needless to say that things look pretty easy with PowerMocks (Mockito api). They look easy because they are easy with PowerMocks! Yes! you can with PowerMocks (Mockito api)!
Feedback, questions and comments are always welcome.