Your SlideShare is downloading. ×
Effective TDD - Less is more
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Effective TDD - Less is more


Published on

Published in: Technology

1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. Effective TDDLess is MoreBen Lau2013
  • 2. Conversation with aprogrammer using TDDStory (1)
  • 3. “TDD is really excellent”“It helps me to fix a lot of bugand speed up the development”The programmer said
  • 4. Then the programmer askCan I ask QA towrite more testcode for me?
  • 5. TDD is Test DrivenDevelopmentBut it is NOT asking you towrite a lot of test code
  • 6. How deep are your unit tests?“I get paid for code that works, not for tests, so my philosophy isto test as little as possible to reach a given level of confidence (Isuspect this level of confidence is high compared to industrystandards, but that could just be hubris). If I dont typically makea kind of mistake (like setting the wrong variables in aconstructor), I dont test for it. I do tend to make sense of testerrors, so Im extra careful when I have logic with complicatedconditionals. When coding on a tea...” [snipped]by Kent BeckThe creator of TDDA post in stackoverflowSource:
  • 7. Why we dont write test case“It is too early! Do it when the project finished!”“It is working. We dont need test program”“Lets QA do it!”“Testing is not real work.”About 261,000,000 results (0.55 seconds)
  • 8. At the end , you wont write any testing codeSource :
  • 9. In my opinion...We dont write test codejust because...It is not funny
  • 10. Writing test code is boring and useless?“I have confidence with my code,why need to write extra code toprove it work and the result isjust to print “OK”?”“It is just wasting of time. ”
  • 11. However , it is not rareAutomated testing code is necessary but people hate itSource:
  • 12. Make it fun by make it failEnjoy writing testing code – Tip 1
  • 13. Story (2) – Pair programmingMissionRefactor the program with test codedue to requirement changes
  • 14. The conversationBen : “So this piece of code is wrong?”Programmer: “NO! It is correct.” (beforerequirement change)Ben : “Nevermind. I will make it wrong no matteris it working now. (smile)”
  • 15. So make it fun by make it fail1) Dont touch the main program2) Modify the test code according to therequirement changes3) Run it
  • 16. Expected result - Red LightCompile error / throw undefinedexception● If it is green (surprise!):– Your test code is wrong?● May be you have misunderstood therequirement– The code base has supported thefeature already?● Finished!– Someone disabled the test code?● You find a potential problem
  • 17. Your mission - turn it green● The short term goal – Fix it.● It is an achievement● The definition of “Done” isclear = Pass the test case.● Highly focused on what youare doing
  • 18. Enjoy writing testing code – Tip 2Design your programby write test code first
  • 19. Just write it?● Many project / module start without designdocumentation and lets programmer “justwrite it”.● Many programmers enjoy working in thisway (before the hell of integration andtesting)● Sometimes may discover architecturalfailure but it is already too late to fix
  • 20. Design failure?● Even you have design documentation– It may not be deep enough– It may be wrong● In fact ,the specification / design document andimplementation can be different.● Design failure is usually discovered in implementation● Coding is the most effective way to discover designfailure , but the cost of change is very high
  • 21. Design by writing test code● Write test code before to implement the main program● Just like writing pseudo code but executable● Help you to clarify your intention– How others use your module?– Will it be confusing? Too ugly? Too complicated?– Inconsistent with other module?– Is it testable?– Discover design failure by stand in the point of user without realimplementation.
  • 22. Practice make perfectvar a = [3];console.log(a.length); //1consloe.log(a[0]); //3var a = new Array(3);console.log(a.length); //3consloe.log(typeofa[0]); //undefined● A typical examplecode in text book● Expected output iswritten in comment● Verify the result byhuman eye
  • 23. Turn into test code is easytest("array" , function() {var a = [3];ok(a.length == 1);ok(a[0] == 3);var a = new Array(3);ok(a.length == 3);ok(typeof a[0] ==undefined);});● Describe yourexpectation(Specification / Designplan)● May discover potentialproblem in this phase code examples are embeddedwithin a test framework
  • 24. Less is more
  • 25. Mission● Implement an user account creation RESTful API butno document and your boss ask you to do it now.● It is coded before the real handling code● Design during coding...– The name of test case = mission statement– Try to demonstrate a success and fail case...– Th URL and method is “POST /account”– The successful code should be 201 instead of 200– Fail code : 400
  • 26. exports.createAccount = function(test) {// Mission: Implement an account creation call using node.jsvar app = express();app.use(express.bodyParser());"/account",account.create);request(app) //"supertest" may simulate HTTP call to"/account").expect(400) // Argument mssing, it should return error..end(function(err,res) {if (err) {test.ok(false,err)}}); // A simple test caserequest(app).post("/account").set( Content-Type, application/json ).send({ username : "tester" ,email : "" }).expect(201) // Expected result.end(function(err,res) {if (err) {test.ok(false,err)}test.done();});}
  • 27. Tests Missed / Hidden Requirements● Duplicated username and email ?● Email format checking?● Fields like birthday, age , gender?● Verify database record?● Verify the output content?● The coverage of test is not 100%● Create account is a simple task , 100% coverage of testcode may be 10 times more then the real implementation
  • 28. You dont need 100% coverage in TDD● 100% coverage of test is simply not possible inmany condition● The more the coverage, the more the timeconsumed. (Usually in exponential rate)● But a simple success and fail condition is veryeasy!● TDD turn writing test into a design activity (funny)but not asking to write a lot of test code (veryboring)
  • 29. Write test code only if needed● Example– Design driven● For new API of module– Bug driven● Do it when you got a bug report● Prevent it happen again● Enhance the coverage of test– Complicated code and conditional
  • 30. Conclusion
  • 31. The core activity of TDD● Write test code first● Write failing test case
  • 32. Write test code first● It is not just to verify the work (boring)● Force developer to clarify their intention– What are you going to do?– Verify the design - is it too tight or unfocused?● You may discover design failure during coding● If you have coded the feature , you may not want to change it– Design code in testable way. More easy to debug andextend– Helping the team to understand the features
  • 33. Write failing test case● Set a short term goal : Make it pass (funny~)● Limit the scope● Concentrate your work
  • 34. The benefit● You have automated test codes!● Your code is testable● Testable code is more easy to debug andchange.● “Programmers using pure TDD on new("greenfield") projects reported they only rarelyfelt the need to invoke a debugger”. Quotedfrom Wikipedia
  • 35. Thank youTwitter: @benlaud