Mock

Mock objects have expectations; a test expects a value from a mock object, and during execution, a mock object returns the expected result. Also, mock objects can keep track of the invocation count, that is, the number of times a method on a mock object is invoked.

The following example is a continuation of the ATM example with a mock version. In the previous example, we stubbed the dispense method of the Dispenser interface to throw an exception; here, we'll use a mock object to replicate the same behavior. We'll explain the syntax in Chapter 4, Progressive Mockito.

public class ATMTest { @Mock Dispenser failingDispenser; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void transaction_is_rolledback_when_hardware_fails() ...

Get Mastering Unit Testing Using Mockito and JUnit now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.