writing testable code

17
Writing testable code Andrew Chaa, Team Magnum

Upload: andrew-chaa

Post on 05-Dec-2014

1.314 views

Category:

Documents


5 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Writing Testable Code

Writing testable codeAndrew Chaa, Team Magnum

Page 2: Writing Testable Code

What to test ?

Page 3: Writing Testable Code

Only Business Logic !

Database Engine

Business

UI

Page 4: Writing Testable Code

Only public methods And public properties

Test Business Logic

Page 5: Writing Testable Code

Testable Coding

Page 6: Writing Testable Code

Anti-Pattern

Smart UI

Page 7: Writing Testable Code

Very hard to test in Asp.Net webform

Mixed with .Net version specific code

UI Code

Page 8: Writing Testable Code

So, let’s put the obese UI on a diet

Engine

Business

UI

Engine

Business

UI

Page 9: Writing Testable Code

Only control execution flows Business Agnostic

◦ UI code should not change when business logic changes

Simple UI

Page 10: Writing Testable Code

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

Page 11: Writing Testable Code

Business gets smart

Page 12: Writing Testable Code

Database operation

Inherits BaseBusinessClass

Create a domain object from data◦ Entity / value objects

Service Class

Page 13: Writing Testable Code

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

Page 14: Writing Testable Code

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

Page 15: Writing Testable Code

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

Page 16: Writing Testable Code

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?

Page 17: Writing Testable Code

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