Java Mockito: partially mock methods in a class you are testing

Photo by Bernard Hermant on Unsplash

Recently I came upon an interesting dilemma that probably wasn’t that unusual of a problem. I needed to mock a method that existed in the same class that I was testing.

This problem helped me realize that I hadn’t grasped the concept of a mockito spy.

When you want to mock an entire class you can initialize that class as a mock but if you want to use unmocked functions in that class and still mock some of them you need to initialize the class as a spy.

Here’s how you initialize a class as a Mockito Mock:

Now if you were planning on using some of the methods in the class and mocking the rest you can declare a spy as follows:

Let us look then at a class we are testing called apple:

If we are wanting to mock the method getFiberToSeedRation() and test getQualityOfApple() . You would do it as follows:

Conclusion

If you are trying to unit test use mockito spy to mock part of a class you are trying to fix. I hope this helped someone who was looking for the same thing I was today. Best of luck!

Cheers!

Im a software engineer, react developer, inventor, salesman, family man, religious, and outdoor connoisseur

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store