Member-only story

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

Avery Duffin
2 min readMar 2, 2020

--

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:

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:

--

--

Avery Duffin
Avery Duffin

Written by Avery Duffin

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

No responses yet