Notes on Mockito Tutorial

Russell Bateman
22 August 2011
last update:

I'm working through a tutorial on Mockito and some others to see if this is the technology we want to use in my group at work. If you have time to work through this, it will show you two important things:

  1. How to set up and use Mockito
  2. The workflow of test-driven development.

Fist, I loathe the use of wildcards in Java import statements. Here is the complete set for this tutorial:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.anyString;

Russ' notes

Glossary

replay is the act of object scaffolding to produce and object.

strict mock semantics are when only the methods that are explicitly recorded are accepted as valid. Any method that's not expected causes an exception that fails the test and all the expected methods must be called if the object is to pass verification.

loose mock allows any method called during the replay state to be accepted and if there is not special handling set up for the method, a null or zero is returned. All the expected methods must be called if the object is to pass verification.

A stub is an object that is set up to feed the required inputs into the system under test.
when( ... ).theReturn( ... )

A mock is an object that is used to verify that the system under test interacts as expected with the object(s) it relies on.
verify( ...).methodXxx( ... )

happy-path test is a well defined test case using known input that executes without exception and produces expected output.

Notes to put somewhere

At Is there a difference between asking and telling, the inventor of Mockito says, "In practice: If I stub then it is verified for free, so I don't verify. If I verify then I don't care about the return value, so I don't stub. Either way, I don't repeat myself." This posting is not only interesting for the discussion by its author, but also for the discussion in the comments below.

Brice Dutheil says:

  1. Don't use try...catch in your test methods unless there is a good reason for that. Usually I code tests with @Test(expected = Exception.class) style. It has the benifit to remove the clutter.
  2.  
  3. @Test public testFillingDoesNotRemoveIfNotEnoughInStock(), test is redundant with the annotation, you can get rid of it, what we want is the test to be readable, almost like your native language, I now use the underscored style as the readability of the test intent is easier to read than with camel case. PLEASE NOTE that I ONLY recommand it for tests.
  4.  
  5. You don't need to assert what you just stubbed. i.e.: the hasInventory(anyString(), anyInt()), don't need to be asserted. This line is irrelevant: assertFalse( mockedWarehouse.hasInventory( TALISKER, 5 ) );

Equates and definitions

stub when()

Useful Links