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:
Apple apple = Mockito.mock(Apple.class);
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:
Apple apple = Mockito.spy(Apple.class);
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:
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!