Mockito: stubbing

Learn
2 min readSep 10, 2024

--

Mockito is about isolating dependencies. You call a third party API in your code, and every time you try running against that, you get all kinds of issues — some times, the server is down, some times they did a version upgrade, some times they break the contract. And you are unable to proceed with your own work.

What if you could focus on your own work? This is what I am supposed to do as far as interaction with this third party is concerned. If this party gives me this kind of a response, then I am supposed to do this, this and this.

If I get something else, then I need to do some other specific steps.

Steps, not stubs.

A cigarette stub is what remains of a cigarette. Similary a stub of a java object is just a remnant of the actual object. This stub is not the entire object, but instead has specific restrained behaviors specified on it by the programmer.

That is where Mockito stubs comes in. It lets you stub the behavior. It lets you say that the third party API returns so and so when invoked with so and so arguments. The behavior is pre-determined. No stress of what might happen when I test it this time.

I am supposed to handle five different kinds of responses, and I have five different set of things I need to handle. Write it all up as tests using Mockito, and make code changes to have these tests pass.

Now, you have the peace of mind that you have done what you had promised to do. And if things fail in the real world, chances are that the third party did not meet the pre-conditions established.

when(thirdParty).method(arguments).thenReturn(abc);

myClass.myMethod();

// Expectations
dependencyOne.methodOne should have been called once with so and so parameters
dependencyThree.methodSeven should have been called .. etc

--

--