Using a spy

Replace an awkward collaborator with a Spy in order to get this code under test.

Learning Goals

Session Outline

Connect: How can you test this?

This is a Code Review connect. Today’s exercise is Discount Applier. The DiscountApplier class contains two versions of a method apply that has two different bugs, marked with comments. How could you write tests that would fail because of each bug? Discuss in pairs. Don’t write any code at this point, just talk.

Concept: Test Doubles

Explain what a test double is and how we could use one in this problem.

Demo: Use a Spy

Show how to use a Spy to expose the first bug:

This test should fail because of the bug. Show that if you fix it, the test passes.

You can use a mocking framework or a hand-coded Spy class depending on what you think people will find easiest to understand.

Concrete: Write a test using a test double

Ask people to repeat what you showed in the demo and write a test for the first version of apply. Then they should use the same approach to also get the second apply method under test. Do not change the DiscountApplier class otherwise.

Encourage people to do the first test by hand and after that they can use an AI tool if they want to.

Conclusions: How do you know when you need a test double?

Why did we need a test double in order to test this code? Ask When should you use this?