Progressive Mockito

(For more resources related to this topic, see here.)

Drinking Mockito

Download the latest Mockito binary from the following link and add it to the project dependency:

As of February 2014, the latest Mockito version is 1.9.5.

Configuring Mockito

To add Mockito JAR files to the project dependency, perform the following steps:

  1. Extract the JAR files into a folder.
  2. Launch Eclipse.
  3. Create an Eclipse project named Chapter04.
  4. Go to the Libraries tab in the project build path.
  5. Click on the Add External JARs... button and browse to the Mockito JAR folder.
  6. Select all JAR files and click on OK.

We worked with Gradle and Maven and built a project with the JUnit dependency. In this section, we will add Mockito dependencies to our existing projects.

The following code snippet will add a Mockito dependency to a Maven project and download the JAR file from the central Maven repository (

<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency>

The following Gradle script snippet will add a Mockito dependency to a Gradle project:

testCompile 'org.mockito:mockito-core:1.9.5'

Mocking in action

This section demonstrates the mock objects with a stock quote example. In the real world, people invest money on the stock market—they buy and sell stocks. A stock symbol is an abbreviation used to uniquely identify shares of a particular stock on a particular market, such as stocks of Facebook are registered on NASDAQ as FB and stocks of Apple as AAPL.

We will build a stock broker simulation program. The program will watch the market statistics, and depending on the current market data, you can perform any of the following actions:

  • Buy stocks
  • Sell stocks
  • Hold stocks

The domain classes that will be used in the program are Stock, MarketWatcher, Portfolio, and StockBroker.

Stock represents a real-world stock. It has a symbol, company name, and price.

MarketWatcher looks up the stock market and returns the quote for the stock. A real implementation of a market watcher can be implemented from!_finance. Note that the real implementation will connect to the Internet and download the stock quote from a provider.

Portfolio represents a user's stock data such as the number of stocks and price details. Portfolio exposes APIs for getting the average stock price and buying and selling stocks. Suppose on day one someone buys a share at a price of $10.00, and on day two, the customer buys the same share at a price of $8.00. So, on day two the person has two shares and the average price of the share is $9.00.

The following screenshot represents the Eclipse project structure. You can download the project from the Packt Publishing website and work with the files:

The following code snippet represents the StockBroker class. StockBroker collaborates with the MarketWatcher and Portfolio classes. The perform() method of StockBroker accepts a portfolio and a Stock object:

public class StockBroker { private final static BigDecimal LIMIT = new BigDecimal("0.10"); private final MarketWatcher market; public StockBroker(MarketWatcher market) { = market; } public void perform(Portfolio portfolio,Stock stock) { Stock liveStock = market.getQuote(stock.getSymbol()); BigDecimal avgPrice = portfolio.getAvgPrice(stock); BigDecimal priceGained = liveStock.getPrice().subtract(avgPrice); BigDecimal percentGain = priceGained.divide(avgPrice); if(percentGain.compareTo(LIMIT) > 0) { portfolio.sell(stock, 10); }else if(percentGain.compareTo(LIMIT) < 0){; } } }

Look at the perform method. It takes a portfolio object and a stock object, calls the getQuote method of MarketWatcher, and passes a stock symbol. Then, it gets the average stock price from portfolio and compares the current market price with the average stock price. If the current stock price is 10 percent greater than the average price, then the StockBroker program sells 10 stocks from Portfolio; however, if the current stock price goes down by 10 percent, then the program buys shares from the market to average out the loss.

Why do we sell 10 stocks? This is just an example and 10 is just a number; this could be anything you want.

StockBroker depends on Portfolio and MarketWatcher; a real implementation of Portfolio should interact with a database, and MarketWatcher needs to connect to the Internet. So, if we write a unit test for the broker, we need to execute the test with a database and an Internet connection. A database connection will take time and Internet connectivity depends on the Internet provider. So, the test execution will depend on external entities and will take a while to finish. This will violate the quick test execution principle. Also, the database state might not be the same across all test runs. This is also applicable for the Internet connection service. Each time the database might return different values, and therefore asserting a specific value in your unit test is very difficult.

We'll use Mockito to mock the external dependencies and execute the test in isolation. So, the test will no longer be dependent on real external service, and therefore it will be executed quickly.

Mocking objects

A mock can be created with the help of a static mock() method as follows:

import org.mockito.Mockito; public class StockBrokerTest { MarketWatcher marketWatcher = Mockito.mock(MarketWatcher.class); Portfolio portfolio = Mockito.mock(Portfolio.class); }

Otherwise, you can use Java's static import feature and static import the mock method of the org.mockito.Mockito class as follows:

import static org.mockito.Mockito.mock; public class StockBrokerTest { MarketWatcher marketWatcher = mock(MarketWatcher.class); Portfolio portfolio = mock(Portfolio.class); }

There's another alternative; you can use the @Mock annotation as follows:

import org.mockito.Mock; public class StockBrokerTest { @Mock MarketWatcher marketWatcher; @Mock Portfolio portfolio; }

However, to work with the @Mock annotation, you are required to call MockitoAnnotations.initMocks( this ) before using the mocks, or use MockitoJUnitRunner as a JUnit runner.

The following code snippet uses MockitoAnnotations to create mocks:

import static org.junit.Assert.assertEquals; import org.mockito.MockitoAnnotations; public class StockBrokerTest { @Mock MarketWatcher marketWatcher; @Mock Portfolio portfolio; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void sanity() throws Exception { assertNotNull(marketWatcher); assertNotNull(portfolio); } }

The following code snippet uses the MockitoJUnitRunner JUnit runner:

import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class StockBrokerTest { @Mock MarketWatcher marketWatcher; @Mock Portfolio portfolio; @Test public void sanity() throws Exception { assertNotNull(marketWatcher); assertNotNull(portfolio); } }

Before we deep dive into the Mockito world, there are a few things to remember. Mockito cannot mock or spy the following functions: final classes, final methods, enums, static methods, private methods, the hashCode() and equals() methods, anonymous classes, and primitive types.

PowerMock (an extension of EasyMock) and PowerMockito (an extension of the Mockito framework) allows you to mock static and private methods; even PowerMockito allows you to set expectations on new invocations for private member classes, inner classes, and local or anonymous classes. However, as per the design, you should not opt for mocking private/static properties—it violates the encapsulation. Instead, you should refactor the offending code to make it testable.

Change the Portfolio class, create the final class, and rerun the test; the test will fail as the Portfolio class is final, and Mockito cannot mock a final class.

The following screenshot shows the JUnit output:

Stubbing methods

We read about stubs in ,Test Doubles. The stubbing process defines the behavior of a mock method such as the value to be returned or the exception to be thrown when the method is invoked.

The Mockito framework supports stubbing and allows us to return a given value when a specific method is called. This can be done using Mockito.when() along with thenReturn ().

The following is the syntax of importing when:

import static org.mockito.Mockito.when;

The following code snippet stubs the getQuote(String symbol) method of MarcketWatcher and returns a specific Stock object:

import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class StockBrokerTest { @Mock MarketWatcher marketWatcher; @Mock Portfolio portfolio; @Test public void marketWatcher_Returns_current_stock_status() { Stock uvsityCorp = new Stock("UV", "Uvsity Corporation",
new BigDecimal("100.00")); when (marketWatcher.getQuote( anyString ())). thenReturn (uvsityCorp); assertNotNull(marketWatcher.getQuote("UV")); } }

A uvsityCorp stock object is created with a stock price of $100.00 and the getQuote method is stubbed to return uvsityCorp whenever the getQuote method is called. Note that anyString() is passed to the getQuote method, which means whenever the getQuote method will be called with any String value, the uvsityCorp object will be returned.

The when() method represents the trigger, that is, when to stub.

The following methods are used to represent what to do when the trigger is triggered:

  • thenReturn(x): This returns the x value.
  • thenThrow(x): This throws an x exception.
  • thenAnswer(Answer answer): Unlike returning a hardcoded value, a dynamic user-defined logic is executed. It's more like for fake test doubles, Answer is an interface.
  • thenCallRealMethod(): This method calls the real method on the mock object.

The following code snippet stubs the external dependencies and creates a test for the StockBroker class:

import; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class StockBrokerTest { @Mock MarketWatcher marketWatcher; @Mock Portfolio portfolio; StockBroker broker; @Before public void setUp() { broker = new StockBroker(marketWatcher); } @Test public void when_ten_percent_gain_then_the_stock_is_sold() { //Portfolio's getAvgPrice is stubbed to return $10.00 when(portfolio.getAvgPrice(isA(Stock.class))). thenReturn(new BigDecimal("10.00")); //A stock object is created with current price $11.20 Stock aCorp = new Stock("A", "A Corp", new BigDecimal("11.20")); //getQuote method is stubbed to return the stock when(marketWatcher.getQuote(anyString())).thenReturn(aCorp); //perform method is called, as the stock price increases // by 12% the broker should sell the stocks broker.perform(portfolio, aCorp); //verifying that the broker sold the stocks verify(portfolio).sell(aCorp,10); } }

The test method name is when_ten_percent_gain_then_the_stock_is_sold; a test name should explain the intention of the test. We use underscores to make the test name readable. We will use the when_<<something happens>>_then_<<the action is taken>> convention for the tests.

In the preceding test example, the getAvgPrice() method of portfolio is stubbed to return $10.00, then the getQuote method is stubbed to return a hardcoded stock object with a current stock price of $11.20. The broker logic should sell the stock as the stock price goes up by 12 percent.

The portfolio object is a mock object. So, unless we stub a method, by default, all the methods of portfolio are autostubbed to return a default value, and for the void methods, no action is performed. The sell method is a void method; so, instead of connecting to a database to update the stock count, the autostub will do nothing.

However, how will we test whether the sell method was invoked? We use Mockito.verify.

The verify() method is a static method, which is used to verify the method invocation. If the method is not invoked, or the argument doesn't match, then the verify method will raise an error to indicate that the code logic has issues.

Verifying the method invocation

To verify a redundant method invocation, or to verify whether a stubbed method was not called but was important from the test perspective, we should manually verify the invocation; for this, we need to use the static verify method.

Why do we use verify?

Mock objects are used to stub external dependencies. We set an expectation, and a mock object returns an expected value. In some conditions, a behavior or method of a mock object should not be invoked, or sometimes, we may need to call the method N (a number) times. The verify method verifies the invocation of mock objects.

Mockito does not automatically verify all stubbed calls.

If a stubbed behavior should not be called but the method is called due to a bug in the code, verify flags the error though we have to verify that manually. The void methods don't return values, so you cannot assert the returned values. Hence, verify is very handy to test the void methods.

Verifying in depth

The verify() method has an overloaded version that takes Times as an argument. Times is a Mockito framework class of the org.mockito.internal.verification package, and it takes wantedNumberOfInvocations as an integer argument.

If 0 is passed to Times, it infers that the method will not be invoked in the testing path. We can pass 0 to Times(0) to make sure that the sell or buy methods are not invoked. If a negative number is passed to the Times constructor, Mockito throws MockitoException - org.mockito.exceptions.base.MockitoException, and this shows the Negative value is not allowed here error.

The following methods are used in conjunction with verify:

  • times(int wantedNumberOfInvocations): This method is invoked exactly n times; if the method is not invoked wantedNumberOfInvocations times, then the test fails.
  • never(): This method signifies that the stubbed method is never called or you can use times(0) to represent the same scenario. If the stubbed method is invoked at least once, then the test fails.
  • atLeastOnce(): This method is invoked at least once, and it works fine if it is invoked multiple times. However, the operation fails if the method is not invoked.
  • atLeast(int minNumberOfInvocations): This method is called at least n times, and it works fine if the method is invoked more than the minNumberOfInvocations times. However, the operation fails if the method is not called minNumberOfInvocations times.
  • atMost(int maxNumberOfInvocations): This method is called at the most n times. However, the operation fails if the method is called more than minNumberOfInvocations times.
  • only(): The only method called on a mock fails if any other method is called on the mock object. In our example, if we use verify(portfolio, only()).sell(aCorp,10);, the test will fail with the following output:

    The test fails in line 15 as portfolio.getAvgPrice(stock) is called.

  • timeout(int millis): This method is interacted in a specified time range.

Verifying zero and no more interactions

The verifyZeroInteractions(Object... mocks) method verifies whether no interactions happened on the given mocks.

The following test code directly calls verifyZeroInteractions and passes the two mock objects. Since no methods are invoked on the mock objects, the test passes:

@Test public void verify_zero_interaction() { verifyZeroInteractions(marketWatcher,portfolio); }

The verifyNoMoreInteractions(Object... mocks) method checks whether any of the given mocks has any unverified interaction. We can use this method after verifying a mock method to make sure that nothing else was invoked on the mock.

The following test code demonstrates verifyNoMoreInteractions:

@Test public void verify_no_more_interaction() { Stock noStock = null; portfolio.getAvgPrice(noStock); portfolio.sell(null, 0); verify(portfolio).getAvgPrice(eq(noStock)); //this will fail as the sell method was invoked verifyNoMoreInteractions(portfolio); }

The following is the JUnit output:

The following are the rationales and examples of argument matchers.

Using argument matcher

ArgumentMatcher is a Hamcrest matcher with a predefined describeTo() method. ArgumentMatcher extends the org.hamcrest.BaseMatcher package. It verifies the indirect inputs into a mocked dependency.

The Matchers.argThat(Matcher) method is used in conjunction with the verify method to verify whether a method is invoked with a specific argument value.

ArgumentMatcher plays a key role in mocking. The following section describes the context of ArgumentMatcher.

Mock objects return expected values, but when they need to return different values for different arguments, argument matcher comes into play. Suppose we have a method that takes a player name as input and returns the total number of runs (a run is a point scored in a cricket match) scored as output. We want to stub it and return 100 for Sachin and 10 for xyz. We have to use argument matcher to stub this.

Mockito returns expected values when a method is stubbed. If the method takes arguments, the argument must match during the execution; for example, the getValue(int someValue) method is stubbed in the following way:

when(mockObject.getValue(1)).thenReturn(expected value);

Here, the getValue method is called with mockObject.getValue(100). Then, the parameter doesn't match (it is expected that the method will be called with 1, but at runtime, it encounters 100), so the mock object fails to return the expected value. It will return the default value of the return type—if the return type is Boolean, it'll return false; if the return type is object, then null, and so on.

Mockito verifies argument values in natural Java style by using an equals() method. Sometimes, we use argument matchers when extra flexibility is required.

Mockito provides built-in matchers such as anyInt(), anyDouble(), anyString(), anyList(), and anyCollection().

More built-in matchers and examples of custom argument matchers or Hamcrest matchers can be found at the following link:

Examples of other matchers are isA(java.lang.Class<T> clazz), any(java.lang.Class<T> clazz), and eq(T) or eq(primitive value).

The isA argument checks whether the passed object is an instance of the class type passed in the isA argument. The any(T) argument also works in the same way.

Why do we need wildcard matchers?

Wildcard matchers are used to verify the indirect inputs to the mocked dependencies. The following example describes the context.

In the following code snippet, an object is passed to a method and then a request object is created and passed to service. Now, from a test, if we call the someMethod method and service is a mocked object, then from test, we cannot stub callMethod with a specific request as the request object is local to the someMethod:

public void someMethod(Object obj){ Request req = new Request(); req.setValue(obj); Response resp = service.callMethod(req); }

If we are using argument matchers, all arguments have to be provided by matchers.

We're passing three arguments and all of them are passed using matchers:

verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));

The following example will fail because the first and the third arguments are not passed using matcher:

verify(mock).someMethod(1, anyString(), "third argument");

The ArgumentMatcher class

The ArgumentMatcher class allows the creation of customized argument matchers. ArgumentMatcher is a Hamcrest matcher with the predefined describeTo() method.

Use the Matchers.argThat(org.hamcrest.Matcher) method and pass an instance of the Hamcrest matcher.

Consider the MarketWatcher class; it takes a stock symbol and then gets the quote from the market.

We will create a mock for the MarketWatcher.getQuote method that takes a String object. We wish to make this method conditional. If a blue chip stock symbol is passed to the method, then the method will return $1000.00; otherwise, it will return $5.00.

How will we identify a blue chip share? A blue chip share is a common stock of a well-known company whose value and dividends are reliable and usually safe for investment. For example, if the stock symbol is FB or AAPL, we will consider the stock as a blue chip stock.

Let us create a custom matcher to identify blue chip stocks. The following code shows a custom argument matcher:

class BlueChipStockMatcher extends ArgumentMatcher<String>{ @Override public boolean matches(Object symbol) { return "FB".equals(symbol) || "AAPL".equals(symbol); } }

The following class extends BlueChipStockMatcher and then negates the result to indicate that the stock is not a blue chip stock:

class OtherStockMatcher extends BlueChipStockMatcher{ @Override public boolean matches(Object symbol) { return !super.matches(symbol); } }

The following test uses the custom matchers to sell the shares:

@Test public void argument_matcher() { when(portfolio.getAvgPrice(isA(Stock.class))). thenReturn(new BigDecimal("10.00")); Stock blueChipStock = new Stock("FB", "FB Corp", new BigDecimal(1000.00)); Stock otherStock = new Stock("XY", "XY Corp", new BigDecimal(5.00)); when(marketWatcher.getQuote(argThat(new BlueChipStockMatcher ()))).thenReturn( blueChipStock ); when(marketWatcher.getQuote(argThat(new OtherStockMatcher ()))).thenReturn( otherStock ); broker.perform(portfolio, blueChipStock); verify(portfolio).sell(blueChipStock,10); broker.perform(portfolio, otherStock); verify(portfolio, never() ).sell(otherStock,10); }

In the preceding code, marketWatcher is stubbed to return a blue chip share when the stock symbol is FB or AAPL; otherwise, it returns a normal stock.

Throwing exceptions

Unit tests are not meant for only happy path testing. We should test our code for the failure conditions too. Mockito provides an API to raise an error during testing. Suppose we are testing a flow where we compute a value and then print it to a printer. If the printer is not configured, or a network error happens, or a page is not loaded, the system throws an exception. We can test this using Mockito's exception APIs.

How do we test exceptional conditions such as database access failure?

Mockito provides a method called thenThrow(Throwable); this method throws an exception when the stubbed method is invoked.

We will stub the getAvgPrice method to throw an exception when the method is called, as follows:

@Test(expected = IllegalStateException.class) public void throwsException() throws Exception { when(portfolio.getAvgPrice(isA(Stock.class))).thenThrow(new
IllegalStateException("Database down")); portfolio.getAvgPrice(new Stock(null, null, null)); }

We are stubbing portfolio to throw an exception when getAvgPrice() is invoked. The following is the syntax to throw an exception from a method that returns void:


The buy method in Portfolio is a void method; we will stub the buy method to throw an exception. The following test code throws IllegalStateException when the buy method is invoked on the portfolio object. Note that doThrow().when() will be used to raise the error from the buy method:

@Test(expected = IllegalStateException.class) public void throwsException_void_methods() throws Exception { doThrow (new IllegalStateException()). when(portfolio).buy(isA(Stock.class)); Stock(null, null, null)); }

Stubbing consecutive calls

Stubbing a method for consecutive calls is required in the following situations:

  • Calling a stubbed method in a loop when you need different results for different calls
  • When you need one invocation to throw an exception and other invocations to return a value

We need to test a condition where the first call will return a value, the next call should not find any value, and then again it should return a value.

The varargs version of thenReturn(objects...) takes comma-separated return values and returns the arguments in order such that if we pass two arguments to the thenReturn method, then the first call to the stubbed method will return the first argument. Thereafter, all other calls will return the second argument, as shown in the following code:

@Test public void consecutive_calls() throws Exception { Stock stock = new Stock(null, null, null); when(portfolio.getAvgPrice(stock)).thenReturn(BigDecimal.TEN,BigDecimal.ZERO); assertEquals(BigDecimal.TEN, portfolio.getAvgPrice(stock)); assertEquals(BigDecimal.ZERO, portfolio.getAvgPrice(stock)); assertEquals(BigDecimal.ZERO, portfolio.getAvgPrice(stock)); }

Note that thenReturn takes two values: BigDecimal.TEN and BigDecimal.ZERO. The first call to getAvgPrice will return BigDecimal.TEN, and then each call will return BigDecimal.ZERO.

This can be done in another way—Mockito methods return stub objects and follow a builder pattern to allow a chain of calls.

In the following example, thenReturn and thenThrow are combined to build a chain of response. After the second call, each getAvgPrice invocation will throw an exception:


Stubbing with an Answer

Stubbed methods return a hardcoded value but cannot return an on the fly result. The Mockito framework provides the callbacks to compute the on the fly results.

Mockito allows stubbing with the generic Answer interface. This is a callback; when a stubbed method on a mock object is invoked, the answer(InvocationOnMock invocation) method of the Answer object is called. This Answer object's answer() method returns the actual object.

The syntax of Answer is when(mock.someMethod()).thenAnswer(new Answer() {…}); or when(mock.someMethod()).then(answer);, which is similar to thenReturn() and thenThrow().

The Answer interface is defined as follows:

public interface Answer<T> { T answer(InvocationOnMock invocation) throws Throwable; }

The InvocationOnMock argument is an important part of callback. It can return the arguments passed to the method and also return the mock object as follows:

Object[] args = invocation.getArguments(); Object mock = invocation.getMock();

Add a new method to the Portfolio class to return the total stock value. We are using a mock Portfolio instance, so we cannot return the total stock value. We can fix this using Answer and make the test totally configurable.

When a new stock is bought, we will store the stock in HashMap, and when the getCurrentValue method will be invoked, we will compute the value dynamically from HashMap. So, we need two Answer objects, one to store stocks and the other to compute the total.

The following code snippet creates two Answer classes. Add HashMap to the test class:

Map<String, List<Stock>> stockMap = new HashMap<String, List<Stock>>();

One can buy 10 stocks of Facebook or 10 different stocks. The stockMap object stores a key-value pair. The key is the Stock symbol and the value is a list of stocks. 10 Facebook stocks will add a single key, FB, and a list of 10 Facebook stocks. An Apple stock will add another entry to the map with an AAPL key and value and a list with a single Apple stock.

The following Answer implementation is called when the buy method is invoked. The invocationOnMock object returns the arguments, and the buy method accepts only one argument, that is, a Stock object. So, type casted the 0th argument to Stock. Then, insert Stock to the stockMap object:

class BuyAnswer implements Answer<Object>{ @Override public Object answer(InvocationOnMock invocation) throws Throwable { Stock newStock = (Stock)invocation.getArguments()[0]; List<Stock> stocks = stockMap.get(newStock.getSymbol()); if(stocks != null) { stocks.add(newStock); }else { stocks = new ArrayList<Stock>(); stocks.add(newStock); stockMap.put(newStock.getSymbol(), stocks); } return null; } }

The following answer object implements the total price computation logic:

class TotalPriceAnswer implements Answer<BigDecimal>{ @Override public BigDecimal answer(InvocationOnMock invocation) throws Throwable { BigDecimal totalPrice = BigDecimal.ZERO; for(String stockId: stockMap.keySet()) { for(Stock stock:stockMap.get(stockId)) { totalPrice = totalPrice.add(stock.getPrice()); } } return totalPrice; } }

The getCurrentValue() method will be stubbed to return the preceding answer implementation.

The following JUnit test code uses the TotalPriceAnswer method:

@Test public void answering() throws Exception { stockMap.clear(); doAnswer(new BuyAnswer()).when(portfolio). buy(isA(Stock.class)); when(portfolio.getCurrentValue()). then(new TotalPriceAnswer()); Stock("A", "A", BigDecimal.TEN)); Stock("B", "B", BigDecimal.ONE)); assertEquals(new BigDecimal("11"), portfolio.getCurrentValue()); }

Check that the stockMap object is cleared to remove existing data. Then, the void buy method is stubbed to add stocks to stockMap using the doAnswer method, and then the getCurrentValue method is stubbed to the TotalPriceAnswer answer.

Spying objects

A Mockito spy object allows us to use real objects instead of mocks by replacing some of the methods with the stubbed ones. This behavior allows us to test the legacy code; one cannot mock a class that needs to be tested. Legacy code comes with methods that cannot be tested, but other methods use them; so, these methods need to be stubbed to work with the other methods. A spy object can stub the nontestable methods so that other methods can be tested easily.

Once an expectation is set for a method on a spy object, then spy no longer returns the original value. It starts returning the stubbed value, but still it exhibits the original behavior for the other methods that are not stubbed.

Mockito can create a spy of a real object. Unlike stubbing, when we use spy, the real methods are called (unless a method was stubbed).

Spy is also known as partial mock; one example of the use of spy in the real world is dealing with legacy code.

Declaration of spy is done using the following code:

SomeClass realObject = new RealImplemenation(); SomeClass spyObject = spy(realObject);

The following is a self-explanatory example of spy:

@Test public void spying() throws Exception { Stock realStock = new Stock("A", "Company A", BigDecimal.ONE); Stock spyStock = spy(realStock); //call real method from spy assertEquals("A", spyStock.getSymbol()); //Changing value using spy spyStock.updatePrice(BigDecimal.ZERO); //verify spy has the changed value assertEquals(BigDecimal.ZERO, spyStock.getPrice()); //Stubbing method when(spyStock.getPrice()).thenReturn(BigDecimal.TEN); //Changing value using spy spyStock.updatePrice(new BigDecimal("7")); //Stubbed method value 10.00 is returned NOT 7 assertNotEquals(new BigDecimal("7"), spyStock.getPrice()); //Stubbed method value 10.00 assertEquals(BigDecimal.TEN, spyStock.getPrice()); }

Stubbing void methods

In the Throwing exceptions section of this article, we learned that doThrow is used for throwing exceptions for the void methods. The Stubbing with an Answer section of this article showed you how to use doAnswer for the void methods.

In this section, we will explore the other void methods: doNothing, doReturn, doThrow, and doCallRealMethod.

The doNothing() API does nothing. By default, all the void methods do nothing. However, if you need consecutive calls on a void method, the first call is to throw an error, the next call is to do nothing, and then the next call to perform some logic using doAnswer() and then follow this syntax:

doThrow(new RuntimeException()).

//this call throws exception
// this call does nothing

The doCallRealMethod() API is used when you want to call the real implementation of a method on a mock or a spy object as follows:


The doReturn() method is similar to stubbing a method and returning an expected value. However, this is used only when when(mock).thenReturn(return) cannot be used.

The when-thenReturn method is more readable than doReturn(); also, doReturn() is not a safe type. The thenReturn method checks the method return types and raises a compilation error if an unsafe type is passed.

Here is the syntax for using the doReturn() test:


The following code snippet provides an example of unsafe usage of doReturn:

@Test public void doReturn_is_not_type_safe() throws Exception { //then return is type safe- It has to return a BigDecimal when(portfolio.getCurrentValue()).thenReturn(BigDecimal.ONE); //method call works fine portfolio.getCurrentValue(); //returning a String instead of BigDecimal doReturn("See returning a String"). when(portfolio.getCurrentValue()); //this call will fail with an error portfolio.getCurrentValue(); }

The following screenshot shows how the test fails:

Spying real objects and calling real methods on a spy has side effects; to counter this side effect, use doReturn() instead of thenReturn().

The following code describes the side effect of spying and calling thenReturn():

@Test public void doReturn_usage() throws Exception { List<String> list = new ArrayList<String>(); List<String> spy = spy(list); //impossible the real list.get(0) is called and fails //with IndexOutofBoundsException, as the list is empty when(spy.get(0)).thenReturn("not reachable"); }

In the preceding code, the spy object calls a real method while trying to stub get(index), and unlike the mock objects, the real method was called and it failed with an ArrayIndexOutOfBounds error.

The following screenshot displays the failure message:

This can be protected using doReturn() as shown in the following code, but note that typically we don't mock lists or domain objects; this is just an example:

@Test public void doReturn_usage() throws Exception { List<String> list = new ArrayList<String>(); List<String> spy = spy(list); //doReturn fixed the issue doReturn("now reachable").when(spy).get(0); assertEquals("now reachable", spy.get(0)); }

Capturing arguments with ArgumentCaptor

ArgumentCaptor is used to verify the arguments passed to a stubbed method. Sometimes, we compute a value, then create another object using the computed value, and then call a mock object using that new object. This computed value is not returned from the original method, but it is used for some other computation.

ArgumentCaptor provides an API to access objects that are instantiated within the method under the test.

The following code snippet explains the problem behind the inaccessibility of the method arguments:

public void buildPerson(String firstName, String lastName,
String middleName, int age){ Person person = new Person(); person.setFirstName(firstName); person.setMiddleName(middleName); person.setLastName(lastName); person.setAge(age); this,; }

We are passing a first name, middle name, last name, and an age to the buildPerson method. This method creates a Person object and sets the name and age to it. Finally, it invokes the personService class and saves the person object to a database.

Here, we cannot stub the save behavior of personService from a JUnit test with a specific value since the Person object is created inside the method. We can mock save using a generic matcher object such as isA(Person.class) and then verify whether the Person object contains the correct name and age using the argument captor.

Mockito verifies argument values in natural Java style by using an equals() method. This is also the recommended way of matching arguments because it makes tests clean and simple. In some situations though, it is necessary to assert on certain arguments after the actual verification.

The following code uses two ArgumentCaptors and verifies whether it uses a specific stock symbol, A, and not any other value while calling the method:

public void argument_captor() throws Exception {
new BigDecimal("10.00"));
Stock aCorp = new Stock("A", "A Corp", new
broker.perform(portfolio, aCorp);
ArgumentCaptor<String> stockIdCaptor =
assertEquals("A", stockIdCaptor.getValue());
//Two arguments captured
ArgumentCaptor<Stock> stockCaptor =
ArgumentCaptor<Integer> stockSellCountCaptor =
assertEquals("A", stockCaptor.getValue().getSymbol());
assertEquals(10, stockSellCountCaptor.getValue().intValue());

Check that ArgumentCaptor takes a Class type in the forClass method and then the captor is passed to the verify method to collect the argument details. The sell method takes two arguments, Stock and Integer. So, two ArgumentCaptors are created. The stockCaptor object captures the Stock argument and stockSellCountCaptor captures the stock quantity. Finally, the values are compared to verify whether the correct values were passed to the sell method.

Verifying the invocation order

Mockito facilitates verifying if interactions with a mock were performed in a given order using the InOrder API. It allows us to create InOrder of mocks and verify the call order of all calls of all mocks.

The following test sequentially invokes the getAvgPrice, getCurrentValue, getQuote, and buy methods, but verifies whether the buy() method is invoked before the getAvgPrice() method. So, the verification order is wrong and hence the test fails:

@Test public void inorder() throws Exception { Stock aCorp = new Stock("A", "A Corp", new BigDecimal(11.20)); portfolio.getAvgPrice(aCorp); portfolio.getCurrentValue(); marketWatcher.getQuote("X");; InOrder inOrder=inOrder(portfolio,marketWatcher); inOrder.verify(portfolio).buy(isA(Stock.class)); inOrder.verify(portfolio).getAvgPrice(isA(Stock.class)); }

The following screenshot shows the error message output:

Reordering the verification sequence, we fixed the test as follows:

@Test public void inorder() throws Exception { Stock aCorp = new Stock("A", "A Corp", new BigDecimal(11.20)); portfolio.getAvgPrice(aCorp); portfolio.getCurrentValue(); marketWatcher.getQuote("X");; InOrder inOrder=inOrder(portfolio,marketWatcher); inOrder.verify(portfolio).getAvgPrice(isA(Stock.class)); inOrder.verify(portfolio).getCurrentValue(); inOrder.verify(marketWatcher).getQuote(anyString()); inOrder.verify(portfolio).buy(isA(Stock.class)); }

Changing the default settings

We learned that nonstubbed methods of a mock object return default values such as null for an object and false for a Boolean. However, Mockito allows us to change the default settings.

The following are the allowed settings:

  • RETURNS_DEFAULTS: This is the default setting. It returns null for object, false for Boolean, and so on.
  • RETURNS_SMART_NULLS: This returns spy of a given type.
  • RETURNS_MOCKS: This returns mocks for objects and the default value for primitives.
  • RETURNS_DEEP_STUBS: This returns a deep stub.
  • CALLS_REAL_METHODS: This calls a real method.

The following example overrides the default Mockito settings and uses different return types:

@Test public void changing_default() throws Exception { Stock aCorp = new Stock("A", "A Corp", new BigDecimal(11.20)); Portfolio pf = Mockito.mock(Portfolio.class); //default null is returned assertNull(pf.getAvgPrice(aCorp)); Portfolio pf1 = Mockito.mock(Portfolio.class, Mockito.RETURNS_SMART_NULLS); //a smart null is returned System.out.println("#1 "+pf1.getAvgPrice(aCorp)); assertNotNull(pf1.getAvgPrice(aCorp)); Portfolio pf2 = Mockito.mock(Portfolio.class, Mockito.RETURNS_MOCKS); //a mock is returned System.out.println("#2 "+pf2.getAvgPrice(aCorp)); assertNotNull(pf2.getAvgPrice(aCorp)); Portfolio pf3 = Mockito.mock(Portfolio.class, Mockito.RETURNS_DEEP_STUBS); //a deep stubbed mock is returned System.out.println("#3 "+pf3.getAvgPrice(aCorp)); assertNotNull(pf3.getAvgPrice(aCorp)); }

The following screenshot shows the console output:

Resetting mock objects

A static method reset(T…) enables resetting mock objects. The reset method should be handled with special care; if you need to reset a mock, you will most likely need another test.

A reset method clears the stubs.

The following code snippet stubs the getAvgPrice method to return a value, but reset clears the stub; after reset, the getAvgPrice method returns NULL:

@Test public void resetMock() throws Exception { Stock aCorp = new Stock("A", "A Corp", new BigDecimal(11.20)); Portfolio portfolio = Mockito.mock(Portfolio.class); when(portfolio.getAvgPrice(eq(aCorp))). thenReturn(BigDecimal.ONE); assertNotNull(portfolio.getAvgPrice(aCorp)); Mockito.reset(portfolio); //Resets the stub, so getAvgPrice returns NULL assertNull(portfolio.getAvgPrice(aCorp)); }

Exploring Mockito annotations

We learned that Mockito supports the @Mock annotation for mocking. Just like @Mock, Mockito supports the following three useful annotations:

  • @Captor: This simplifies the creation of ArgumentCaptor, which is useful when the argument to capture is a super generic class, such as List<Map<String,Set<String>>.
  • @Spy: This creates a spy of a given object. Use it instead of spy (object).
  • @InjectMocks: This injects mock or spy fields into the tested object automatically using a constructor injection, setter injection, or field injection.

Working with inline stubbing

Mockito allows us to create mocks while stubbing it. Basically, it allows creating a stub in one line of code. This can be helpful to keep the test code clean.

For example, some stubs can be created and stubbed at field initialization in a test. We use the Stock objects in almost all tests. We can create a global mock Stock and stub it at definition, as shown in the following code snippet:

Stock globalStock = when(Mockito.mock(Stock.class).getPrice()).
public void access_global_mock() throws Exception {
assertEquals(BigDecimal.ONE, globalStock.getPrice());

Determining mocking details

Mockito.mockingDetails identifies whether a particular object is a mock or a spy, as follows:

@Test public void mocking_details() throws Exception { Portfolio pf1 = Mockito.mock(Portfolio.class, Mockito.RETURNS_MOCKS); BigDecimal result = pf1.getAvgPrice(globalStock); assertNotNull(result); assertTrue(Mockito.mockingDetails(pf1).isMock()); Stock myStock = new Stock(null, null, null); Stock spy = spy(myStock); assertTrue(Mockito.mockingDetails(spy).isSpy()); }

Behavior-driven development with Mockito

BDD is a software engineering process based on TDD. BDD combines the best practices of TDD, domain-driven development (DDD), and object-oriented programming (OOP).

In an agile team, scoping a feature is a mammoth task. The business stakeholders talk about business interests, and the development team talks about technical challenges. BDD provides a universal language that allows useful communication and feedback between the stakeholders.

Dan North developed BDD, created the JBehave framework for BDD, and proposed the following best practices:

  • Unit test names should start with the word should and should be written in the order of the business value
  • Acceptance tests (AT) should be written in a user story manner, such as "As a (role) I want (feature) so that (benefit)"
  • Acceptance criteria should be written in terms of scenarios and implemented as "Given (initial context), when (event occurs), then (ensure some outcomes)"

Let's write a user story for our stock broker simulation:

Story: A stock is sold

  • In order to maximize profit
  • As a Stock broker
  • I want to sell a stock when the price goes up by 10 percent

The following is a scenario example:

Scenario: 10 percent increase in stock price should sell the stock in the market

  • Given a customer previously bought FB stocks at $10.00 per share
  • And he currently has 10 shares left in his portfolio
  • When the FB stock price becomes $11.00

Then I should sell all the FB stocks and the portfolio should have zero FB stocks

Mockito supports the BDD style of writing tests using the given-when-then syntax.

Writing tests in BDD style

In BDD, given represents the initial context and when represents the event or condition. However, Mockito already has a when style of (initial context definition) method stubbing; therefore, when doesn't go well with BDD. Thus, the BDDMockito class introduces an alias so that we can stub method calls with the given(object) method.

The following JUnit test is implemented in BDD style:

@RunWith(MockitoJUnitRunner.class) public class StockBrokerBDDTest { @Mock MarketWatcher marketWatcher; @Mock Portfolio portfolio; StockBroker broker; @Before public void setUp() { broker = new StockBroker(marketWatcher); } @Test public void should_sell_a_stock_when_price_increases_by_ten_percent(){ Stock aCorp = new Stock("FB", "FaceBook", new BigDecimal(11.20)); //Given a customer previously bought 10 'FB' stocks at //$10.00/per share given(portfolio.getAvgPrice(isA(Stock.class))). willReturn(new BigDecimal("10.00")); given(marketWatcher.getQuote(eq("FB"))). willReturn(aCorp); //when the 'FB' stock price becomes $11.00 broker.perform(portfolio, aCorp); //then the 'FB' stocks are sold verify(portfolio).sell(aCorp,10); } }

Note that the test name starts with a should statement. The given syntax of Mockito is used to set the initial context that the portfolio already has FB stocks bought at $10.00 per share and the current FB stock price is $11.00 per share.

The following screenshot shows the test execution output:

The BDD syntax

The following methods are used in conjunction with given:

  • willReturn(a value to be returned): This returns a given value
  • willThrow(a throwable to be thrown): This throws a given exception
  • will(Answer answer) and willAnswer(Answer answer): This is similar to then(answer) and thenAnswer(answer)
  • willCallRealMethod(): This calls the real method on the mock object or spy

    The jMock and EasyMock frameworks are the other two Java-based unit testing frameworks that support mocking for automated unit tests.

    The jMock and EasyMock frameworks provide mocking capabilities, but the syntax is not as simple as Mockito. You can visit the following URLs to explore the frameworks:

    To learn more about BDD and JBehave, visit


In this article, Mockito is described in detail and technical examples are provided to demonstrate the capability of Mockito.

By the end of this article, you will be able to use advanced features of the Mockito framework, and start BDD with Mockito.

Resources for Article:

Further resources on this subject:

You've been reading an excerpt of:

Mastering Unit Testing Using Mockito and JUnit

Explore Title