Stub

A stub delivers indirect inputs to the caller when the stub's methods are called. Stubs are programmed only for the test scope. Stubs may record other information such as the number of times the methods were invoked and so on.

Account transactions should be rolled back if the ATM's money dispenser fails to dispense money. How can we test this when we don't have the ATM machine, or how can we simulate a scenario where the dispenser fails? We can do this using the following code:

public interface Dispenser {
  void dispense(BigDecimal amount) throws DispenserFailed;
}
public class AlwaysFailingDispenserStub implements Dispenser{
  public void dispense(BigDecimal amount) throws DispenserFailed{
    throw new DispenserFailed (ErrorType.HARDWARE,"not  responding");
  }
}
class ATMTest...
  @Test
  public void transaction_is_rolledback_when_hardware_fails() {
    Account myAccount = new Account("John", 2000.00);
    TransactionManager txMgr = TransactionManager.forAccount(myAccount);
    txMgr.registerMoneyDispenser(new AlwaysFailingDispenserStub());
    WithdrawalResponse response = txMgr.withdraw(500.00);
    assertEquals(false, response.wasSuccess());
    assertEquals(2000.00, myAccount.remainingAmount());
  }

In the preceding code, AlwaysFailingDispenserStub raises an error whenever the dispense() method is invoked. It allows us to test the transactional behavior when the hardware is not present.

Mockito allows us to mock interfaces and concrete classes. Using Mockito, you can stub the dispense() method to throw an exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset