Write unit test after an existing production code may be burn your money

Core business requirement
Calculate discount rate base on customer type.
1. platinum: discount rate = 0.15
2. gold: discount rate =0.1
3. silver: discount rate = 0.05
4. future specification, only apply above rules in black friday only
What if? write production code first
if apply code production first, code unit test late: programer can write production code runnable, matching business rules but may be not testable easy (sometime cannot tested)
- we can not write unit test code for core business rule (may be we can write integration test code, it is integration business rule with db or remote api call)
- we need to read code discountRateByMembershipType() line by line to write test code for all case match prod code (for case: platinum, gold, silver, exception)
- Sometime we can’t not write any type of test for discountRateByMembershipType() if inside it’s hard dependency on time. Example In the future when add specification:
only apply core business rule in black friday only
may be you can think it’s easy change local time solve problem to help test business rules (line 3), but my friend what if? when we need call remote time server to get time. In this case we can not control remote time server.
What if? Apply write test first, Code Production late (TDD)
This approach not guarantee you will have good application architecture, but it guarantee you have testable application
Step by step apply TDD:
- Write small unit test code matching with a small business specification.
- After that, write minimal production code support pass above unit test code.
- Repeat that until you don’t have any more specification (business requirement).
First specification: business rule for customer ‘platinum’
When run test_with_platinum_member_will_discount_fifteen_percent() will error because discountByMembershipType method undefined.
So we need write minimal production code match above specification
Second specification: business rule for customer ‘gold’
Again, run test_with_gold_member_will_discount_ten_percent() will display ‘Test Fail’ because production code not exist second rule
So we need write minimal production code match specification for gold customer
Now run test_with_gold_member_will_discount_ten_percent() will display ‘Test Done’
Repeat until don’t have any more specification then final result here
