TDD By Example

There is a discount on the Gatsby hair cream
– buy 1 item get 50% discount on next item.
– there is no offer on ‘Bvlgiri soap’.

Let’s implement our IOffer for the discount offer class- DiscountOnNextItemOffer

Requirement: Apply discount on shopping cart
When: Add 2 unit of ‘Gatsby hair cream’, unit price 30 Rupees.
Then:
The product count of cart should be 1.
– The total price of product should be 45.
– The total value of cart should be 45.0 rupees.

Add a test for above requirement to the test class.

The test will have compilation error since we don’t have getProductByname() method in ShoppingCart. Let’s add the method to the ShoppingCart.

Now If you run the test, it will fail since we have not added any logic for % discount. Refactor the DiscountOnNextItemOffer class.

Now run the test. It will pass without any problem.
TDD-By-Example17

Requirement: Apply discount on shopping cart
When: Add 5 unit of ‘Gatsby hair cream’, unit price 30 Rupees.
Then:
The product count of cart should be 1.
– The total price of product should be 120.
– The total value of cart should be 120.0 rupees.

Add test for the above requirements.

The test will pass without any refactoring.

This is all. Here my aim was to give you a feel of TDD. The presented design may not be optimum and further refactoring may be required. You can keep adding your requirements and follow the cycle- Write failing Test – Write code to make test pass – refactor for the best possible design.

To know more about TDD you can read following books:
Growing Object Oriented Software Guided By Tests
Test Driven Development By Example
Test Driven

  • Yash Khare

    Never seen such a great explanation with easy examples and screenshots ever . Keep up the good work !!!! .

    Just one small thing , I would request you to edit your code by using a BigDecimal instead of a double while representing currency. I hope you might be knowing why I asked you to do it , if not please read :

    https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency

    • Thanks…you liked it. Yes I will make the changes for BigDecimal.

  • Neil

    I think you need a test for getTotalCartValueShouldBeIdempotent()
    :-)