TotT: Friends You Can Depend On
When you want to test code that depends on something that is too difficult or slow to use in a test environment, swap in a test double for the dependency.
A Dummy passes bogus input values around to satisfy an API.
Item item = new Item(ITEM_NAME);
ShoppingCart cart = new ShoppingCart();
cart.add(item, QUANTITY);
assertEquals(QUANTITY, cart.getItem(ITEM_NAME));
A Stub overrides the real object and returns hard-coded values. Testing with stubs only is state-based testing; you exercise the system and then assert that the system is in an expected state.
ItemPricer pricer = new ItemPricer() {
public BigDecimal getPrice(String name){ return PRICE; }
};
ShoppingCart cart = new ShoppingCart(pricer);
cart.add(dummyItem, QUANTITY);
assertEquals(QUANTITY*PRICE, cart.getCost(ITEM_NAME));
A Mock can return values, but it also cares about the way its methods are called (“strict mocks” care about the order of method calls, whereas “lenient mocks” do not.) Testing with mocks is interaction-based testing; you set expectations on the mock, and the mock verifies the expectations as it is exercised. This example uses JMock to generate the mock (EasyMock is similar):
Mockery context = new Mockery();
final ItemPricer pricer = context.mock(ItemPricer.class);
context.checking(new Expectations() {{
one(pricer).getPrice(ITEM_NAME);
will(returnValue(PRICE));
}});
ShoppingCart cart = new ShoppingCart(pricer);
cart.add(dummyItem, QUANTITY);
cart.getCost(ITEM_NAME);
context.assertIsSatisfied();
A Spy serves the same purpose as a mock: returning values and recording calls to its methods. However, tests with spies are state-based rather than interaction-based, so the tests look more like stub style tests.
TransactionLog log = new TransactionLogSpy();
ShoppingCart cart = new ShoppingCart(log);
cart.add(dummyItem, QUANTITY);
assertEquals(1, logSpy.getNumberOfTransactionsLogged());
assertEquals(QUANTITY*PRICE, log.getTransactionSubTotal(1));
A Fake swaps out a real implementation with a simpler, fake implementation. The classic example is implementing an in-memory database.
Repository
ShoppingCart cart = new ShoppingCart(repo);
cart.add(dummyItem, QUANTITY);
assertEquals(1, repo.getTransactions(cart).Count);
assertEquals(QUANTITY, repo.getById(cart.id()).getQuantity(ITEM_NAME));
While this episode used Java for its examples, all of the above “friends” certainly exist in C++, Python, JavaScript, and probably in YOUR favorite language as well.
This comment has been removed by the author.
ReplyDeleteTo help the less test-savvy it would have helped to point out exactly which thing is the stub, fake, etc.
ReplyDeleteHi, cool to have a taxonomy of stubs, mocks and all. Question :
ReplyDelete* what is 'dummy' about the first object ? Isn't that simply calling the method with a valid argument ?
* the second examples implicitly shows a design decision : the ItemPricer interface must exists at all. This has two nice consequences : first the ShoppingCart codes tends to become trivial (simply calling out methods in dependencies in a nice order) ; second, it becomes possible to concentrate one one implementation of ItemPricer that has all the tricky logics.
My question is : at some point, doesn't the ShoppingCartTest come become much more complicated to write than the logic code ? At wich point does it become intersting to 'forget' some test code that would just do wiring between its dependencies ? Any experience with that ?
* The spy example assumes that ShoppingCart communicates with the outer world, doesn't it ?
On the overall, it is only possible to invite such friends if you code has been prepared in the first place. To keep the analogy, it requires a friend room and some beers in the fridge. How do you tester guys manage to get those design decisions made early enough (and probably by other developpers) so that test code is easy to write ?
Thanks for the ToT series, keep up the fun !
Regards
PH
@Pierre-Henri Trivier: This taxonomy of stubs is also presented in the great "xUnit Test Patterns" book.
ReplyDelete