writing testable code
DESCRIPTION
TRANSCRIPT
Writing testable codeAndrew Chaa, Team Magnum
What to test ?
Only Business Logic !
Database Engine
Business
UI
Only public methods And public properties
Test Business Logic
Testable Coding
Anti-Pattern
Smart UI
Very hard to test in Asp.Net webform
Mixed with .Net version specific code
UI Code
So, let’s put the obese UI on a diet
Engine
Business
UI
Engine
Business
UI
Only control execution flows Business Agnostic
◦ UI code should not change when business logic changes
Simple UI
Try not to write more than 10 lines of code in any given method◦ Of course, it’s not for its own sake. If it has more
than 10 lines, it seems to have some business logic.
Possibly, program to interface, not concrete class◦ ICandidateStatRepository repo = new CandidateStatKeytermRepository() ◦ or ◦ ICandidateStatRepository repo = new CandidateStatLocationRepository()
◦ repo.GetCandidateStat(…)
Practically, in UI
Business gets smart
Database operation
Inherits BaseBusinessClass
Create a domain object from data◦ Entity / value objects
Service Class
Does not inherit BaseBusinessClass
Often created from Service class
Add business logic on top of available data◦ public string FullName { ◦ get { return FirstName + “ “ + LastName; }◦ }
Domain Object
Interface is more flexible than inheritance
UI can program to interface
◦ IMarketing _eloquaTag◦ _eloquaTag = new EloquaTagBlank(); // BaseWebPage◦ _eloquaTag = new EloquaTagDefault(true); // SiteHome◦ _eloquaTag = new EloquaTagDefault(); // BaseRecruiterPage◦ _eloquaTag = new EloquaTagDefault(); // LoginNewUser
Let’s use Interface
Different implementation
◦ IMarketing _eloquaTag◦ _eloquaTag = new EloquaTagBlank(); // BaseWebPage◦ _eloquaTag = new EloquaTagDefault(true); // SiteHome◦ _eloquaTag = new EloquaTagDefault(); // BaseRecruiterPage◦ _eloquaTag = new EloquaTagDefault(); // LoginNewUser
Same method
◦ _eloquaTag.GetTag()
Program to Interface
Just make the code in a better state than what you found it in
◦ Shorter UI code◦ Extract Method◦ Use Domain object, if possible
What about legacy?
Make your code testable by
Try no more than 10 lines of code in UI methods
Program to an interface
Use Domain business objects
In summary