Book Image

Mastering Unit Testing Using Mockito and JUnit

By : Sujoy Acharya
Book Image

Mastering Unit Testing Using Mockito and JUnit

By: Sujoy Acharya

Overview of this book

Table of Contents (17 chapters)
Mastering Unit Testing Using Mockito and JUnit
About the Author
About the Reviewers


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 {

  @Test  public void transaction_is_rolledback_when_hardware_fails() throws DispenserFailed {
    Account myAccount = new Account(2000.00, "John");
    TransactionManager txMgr = TransactionManager.forAccount(myAccount);