TDD By Example

There is an offer on Gatsby hair cream –
buy x item get y item free– if you buy 2 gatsby hair cream you will get 1 free.
there is no offer on ‘Bvlgiri soap’.

Requirement: Apply offer 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 value of cart should be 120 rupees.

It’s time to accommodate offer in our Shopping Cart Application.
As we can see that the ShoppingCart class has all the products and we are going to apply offers on the products. Therefore ShoppingCart should know about the offers. Currently we have two types of offer- Buy x items get y items free and no offer. We can’t create all the offers in ShoppingCart. As a matter of fact an offer related to a product should be passed by the client to the ShoppingCart so that cart can apply the offer specific to a particular product.

Create an interface IOffer

Now create two implementation- BuyXItemGetYItemFreeOffer and NoOffer

It’s time to add a new test for above requirement. Add 5 unit of “Gatsby hair cream” for 150. Make an assertion for product count 1 and cart value after applying offer is 120.0.

The above tests will not compile since ShoppingCart doesn’t have setOffer() method. Let’s create setOffer(IOffer) method to ShoppingCart.

Now run the test. The last test will fail since we haven’t applied the offer yet and also we have not written any logic for the offer BuyXItemGetYItem free.
TDD-By-Example13

Add offer logic to the class BuyXItemGetYItemFreeOffer.

Apply offer in the ShoppingCart while adding the product to the Cart.

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

Requirement: Add different Products and apply offer to shopping cart
When:
– Add 3 unit of ‘Gatsby hair cream’, unit price 30 Rupees.
– Add 2 unit of ‘Bvlgiri Soap’, unit price 100 Rupees.

Then:
– The product count of the cart should be 2.
– The total value of cart should be 260.0 rupees.

Add a test for the above requirement to our test class.

This test will pass without any refactoring.
Go to the next page – Click on the below red circle with page number.

  • 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()
    :-)