test driven development - the art of fearless programming

38
TDD The Art of Fearless Programming On 06/23/2016 @ SLASSCOM Quality Forum BY CHAMIL JEEWANTHA SOFTWARE ARCHITECT AT ZONE24X7 ALL RIGHTS RESERVED

Upload: chamil-jeewantha

Post on 20-Feb-2017

302 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Test Driven Development - The art of fearless programming

TDDThe Art of Fearless ProgrammingOn 06/23/2016 @ SLASSCOM Quality Forum

BY CHAMIL JEEWANTHASOFTWARE ARCHITECT AT ZONE24X7ALL RIGHTS RESERVED

Page 2: Test Driven Development - The art of fearless programming

What Will You Take Back?

Test Driven Development Answers for What? Why? Who? When? & Where?

Better understanding of a ”Unit”? The difference between,

Unit Test, Integration Test, Test First Development, ATDD

Your belongings ;)

Page 3: Test Driven Development - The art of fearless programming

Some Groundwork

Ask questions Art vs Science

Arts require lots of practice Arts do not require to be proven Overlaps may occur

Most of the points are subjective E.g. Drinking water is good (in general, not always)

Page 4: Test Driven Development - The art of fearless programming

Pitch Report ARE WE ON THE SAME PAGE?

Page 5: Test Driven Development - The art of fearless programming

Some Core Values

Quality is everyone’s responsibility Good test coverage is important Line coverage != test coverage Early testing is better More test cycles are better Architecture plays a big role in Maintainability Maintainability is a significant Quality aspect (Specially

with Agile)

Page 6: Test Driven Development - The art of fearless programming

What is Unit Testing?

A single, indivisible entity The smallest testable part of an

application End User Entire software QA Engineer Single Functionality Architect A Module, Component Developer A Class (OOP), Function

(FP)

Page 7: Test Driven Development - The art of fearless programming

Class? Why not Method (OOP)?

IFA class follows the “Single Responsibility

Principle”

ANDThe methods are cohesive

THENReally hard to use a method independently

Page 8: Test Driven Development - The art of fearless programming

A Unit for a Politician

Drag picture to placeholder or click icon to add

Source: https://en.wikipedia.org/wiki/William_Bennett

Page 9: Test Driven Development - The art of fearless programming

If we have stronger families we will have stronger schools and stronger communities with less poverty and less crime. 

WILLIAM BENNETT, A FORMER UNITED STATES SECRETARY OF EDUCATION

http://www.nytimes.com/roomfordebate/2012/04/24/are-family-values-outdated/stronger-families-stronger-societies

Page 10: Test Driven Development - The art of fearless programming

If we have stronger Units we will have stronger Modules and stronger Software with Rich Features and less Bugs.  

CHAMIL JEEWANTHA, SOFTWARE ARCHITECT @ ZONE24X7

TDD (The Art of Fearless Programming) - SLASSCOM Quality Forum

Page 11: Test Driven Development - The art of fearless programming

Example of a Unit

public class AndCriteria implements Criteria{

private final Criteria criteria1; private final Criteria criteria2;

public AndCriteria(Criteria criteria1, Criteria criteria2) { this.criteria1 = criteria1; this.criteria2 = criteria2; }

public List filter(List values) { List filteredList = criteria1.filter(values); return criteria2.filter(filteredList); }}

Page 12: Test Driven Development - The art of fearless programming

Characteristics of a Good Unit

Not so lengthy Self explained Used by its clients via an interface SOLID Well Tested Compliant with Best Practices (All above +

many more)

Page 13: Test Driven Development - The art of fearless programming

Unit Test

Select the smallest piece of testable software in the application

Isolate it from the rest of the code Determine whether it behaves exactly as you

expect Each unit is tested separately before integrating

them into modules to test the interfaces between modules

Ref: https://msdn.microsoft.com/en-us/library/aa292197(VS.71).aspx

Page 14: Test Driven Development - The art of fearless programming

Characteristics of a Good Unit Test

Automated Thorough Repeatable Independent

Test only one thing Should not rely on each other

Fast Professional (Readable, Maintainable,

Trustworthy)

Page 15: Test Driven Development - The art of fearless programming

Isolating a Unit for Testing

Is this Site Manager good?

Site ManagerHe should by cement from the shop named by

me

Page 16: Test Driven Development - The art of fearless programming

Test Flow

Page 17: Test Driven Development - The art of fearless programming

How to Test

Create a dummy bag of cement Create a dummy hardware shop Instruct the dummy hardware to send the dummy

bag of cement if somebody asks for a bag of cement. Give the address of dummy hardware to the site

manager. Ask for a bag of cement from the site manager Verify whether he has called the given hardware Verify whether we receive the dummy cement bag

back.

Page 18: Test Driven Development - The art of fearless programming

In Java with Mockito

BagOfCement dummyCement = mock(BagOfCement.class);HwShop dummyHw = mock(HwShop.class);When(dummyHw.buyCement()).thenReturn(dummyCement);siteManager.setHwShop(dummyHw);

BagOfCement output = siteManager.askCement();

assertThat(output, is(dummyCement));verify(dummyHw).buyCement();

Page 19: Test Driven Development - The art of fearless programming

Example: Requirement of AndCriteria

The AndCriteria should be an implementation of Criteria

Should filter a given list by first expression and return a filteredList

Should filter the filteredList by the second expression and return the finalList

Page 20: Test Driven Development - The art of fearless programming

Example: Tests for AndCriteria

1. Should_FilterThrough1StAnd2ndExpressions_When_AListIsGiven

2. Should_ThrowException_When_NullIsProvided

Page 21: Test Driven Development - The art of fearless programming

Example: AndCriteria : Test 1

@Testpublic void Should_FilterThrough1StAnd2ndExpressions_When_AListIsGiven(){ List input = // dummy list List lst1 = // dummy list List lst2 = // dummy list

Criteria expr1 = // dummy criteria -> filter(input) returns dummy list (lst1) Criteria expr2 = // dummy criteria -> filter(lst1) returns dummy list (lst2)

AndCriteria criteria = new AndCriteria(expr1, expr2); List output = criteria.filter(input); assertThat(output, is(lst2));}

Page 22: Test Driven Development - The art of fearless programming

Example: AndCriteria : Test 2

@Test (expected = IllegalArgumentException.class)public void Should_ThrowException_When_NullIsProvided() { List input = null AndCriteria criteria = new AndCriteria(expr1, expr2); criteria.filter(input);}

Page 23: Test Driven Development - The art of fearless programming

Example 2: Evaluate Expression

The user should provide an expression with relevant value mappings to its variables. Java Evaluate ((a+b)*3)-2 a=5 b=8

The program should assign a & b values to this expression and evaluate it.

Page 24: Test Driven Development - The art of fearless programming

Code for Evaluating an Expression

class Evaluate{ public static void main(String[] args){ String expr = ... // assign variables with values // evaluate the expr double value = // the output value of the evaluation System.out.println(value); }} Can you write a

“Good” automated test?

Page 25: Test Driven Development - The art of fearless programming

Common Complaints About Unit Testing

Deadline is near, no time to write tests Writing tests takes longer than the production

code Hard to keep the test suite up to date One line of code change breaks 100s of tests

The code works. But

very hard to write unit

tests

So, Refactor your code Not Hard,

Impossible!

Page 26: Test Driven Development - The art of fearless programming

Solution: (TFD)

Test First Development

THE PARADIGM SHIFT

Page 27: Test Driven Development - The art of fearless programming

Rules: TFD

1. Write a(nother) unit test that fails2. Write the minimum production code until

all the tests pass3. Repeat until all your work is done.

Fail Pass

Page 28: Test Driven Development - The art of fearless programming

Test First Benefits (Vs Test Late)

All the benefits of Unit testing+

Write non-testable codes are impossible Test-first forces you to plan before you code It’s faster than writing code without tests It saves you from lengthy code It guides you to build good, SOLID units It increases your confidence (refactor without fear) Acts as a real-time progress bar

Page 29: Test Driven Development - The art of fearless programming

”TDD = TFD + Refactoring

REFACTOR YOUR CODE AT EVERY ITERATION

TDD = Test Driven DevelopmentTFD = Test First Development

Page 30: Test Driven Development - The art of fearless programming

Rules: TDD

1. Write a(nother) unit test that fails2. Write the minimum production code until all

the tests pass3. Refactor your code4. Repeat until all your work is done

Fail Pass

Refactor

Page 31: Test Driven Development - The art of fearless programming

DEMO GET YOUR HANDS DIRTY WITH TDD

Page 32: Test Driven Development - The art of fearless programming

Scenario

For a given Access log file of a web server

Client needs a command line utility to get Percentage of success responses Percentage of failure responses

Time Source Destination Response time

Status

2016/04/22 12:15:05 PM

10.1.5.8 10.1.24.14 55 200

Page 33: Test Driven Development - The art of fearless programming

Approaching with TDD

A Class called “LogAnalyzer” With method “analyze”

Writing the analyze method Reading the file is not matching to this name Separate LogReader should be used

LogReader.read should return List<Request> Two Stats to be calculated

StatCalculator interface List of StatCalculators should be injected to LogAnalyzer

Page 34: Test Driven Development - The art of fearless programming

Tools

IDE (IntelliJ) Test Runner (Junit) Mock libraries (Mockito) Verification (Hamcrest)

Page 35: Test Driven Development - The art of fearless programming

FAQ

Page 36: Test Driven Development - The art of fearless programming

ATDD vs TDD

TDD to drive the design ATDD to make sure all the requirements are

implemented

Page 37: Test Driven Development - The art of fearless programming

Additional time due to TDD?

Beginner Lots of time thinking where to start

Experienced Developer Initially 15 - 17% more

Big time saving later for both

Page 38: Test Driven Development - The art of fearless programming

Thank [email protected]