test driven development - the art of fearless programming

Post on 20-Feb-2017

303 Views

Category:

Software

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

BY CHAMIL JEEWANTHASOFTWARE ARCHITECT AT ZONE24X7ALL RIGHTS RESERVED

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 ;)

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)

Pitch Report ARE WE ON THE SAME PAGE?

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)

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)

Class? Why not Method (OOP)?

IFA class follows the “Single Responsibility

Principle”

ANDThe methods are cohesive

THENReally hard to use a method independently

A Unit for a Politician

Drag picture to placeholder or click icon to add

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

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

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

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); }}

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)

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

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)

Isolating a Unit for Testing

Is this Site Manager good?

Site ManagerHe should by cement from the shop named by

me

Test Flow

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.

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();

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

Example: Tests for AndCriteria

1. Should_FilterThrough1StAnd2ndExpressions_When_AListIsGiven

2. Should_ThrowException_When_NullIsProvided

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));}

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);}

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.

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?

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!

Solution: (TFD)

Test First Development

THE PARADIGM SHIFT

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

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

”TDD = TFD + Refactoring

REFACTOR YOUR CODE AT EVERY ITERATION

TDD = Test Driven DevelopmentTFD = Test First Development

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

DEMO GET YOUR HANDS DIRTY WITH TDD

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

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

Tools

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

FAQ

ATDD vs TDD

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

implemented

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

Thank You!KDCHAMIL@GMAIL.COM

top related