TDD

For beginners

Created by Javi Martín and Miguel Olmos

What is TDD (Test Driven Development)?

  • Development metodology
  • Test before writting any code

Advantages

  • You'll only write the code needed
    • KISS: Keep it simple stupid
    • YAGNI: You aren't gonna need it
  • Detect bugs while developing: cheaper
  • Code more robust, higher quality, better maintainability
  • Bye bye dead code

Advantages

  • Increase your trust in your code
  • Faster development
  • Helps you to meet SOLID*
  • It documents your code
  • Drives you to use design patterns

Disadvantages

  • Learning curve
    • Design patterns
    • SOLID*
    • Unit Testing knowledges
  • Hard to apply over legacy code

TDD development cycle

TDD jargon

  • Code coverage
  • Asserts
  • Unitary test
  • Integration test

TDD jargon

  • Mocks: Assert the mocked method is called without actually calling it
  • Spy: Assert the mocked method is called and calls it
  • Dummies: Override the mocked class and returns a default value
  • Stubs: Return a fake value based on its input

Good practices

  • Don't write logic
  • One test method should assert an use case
  • Clear test method names
  • Tests without interdependency
    • Each test runs independently
    • A test should be run without needing external dependencies

Good practices

  • Only public methods are tested
  • Dependency injection*
  • Tests should run fasttttttttttt

SOLID principles

  • Single responsibility
  • Open-closed
  • Liskov substitution
  • Interface segregation
  • Dependency inversion

Single responsibility

A class should have only a single responsibility

Open-closed

Open for extension, but closed for modification

Liskov substitution

Objects should be replaced by its subtypes without modifying the behaviour

Interface segregation

Many interfaces better than a generic one

Dependency inversion

Depend on abstractions not concretions

  • Inject external dependencies

Let's play

FizzBuzz problem

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz?".

Rules

  • Using TDD development cycle
  • Pair programming

FizzBuzz problem

            
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
... etc up to 100
            
        

Reverse Polish Notation

Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands, in contrast to Polish notation, which puts the operator in the prefix position. It is also known as postfix notation and is parenthesis-free as long as operator arities are fixed.

Reverse Polish Notation

            
5 1 2 + 4 * + 3 - = 14
2 5 3 + * = 16
2 1 12 3 / - + = -1