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
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...