LEARNING TDD/BDD

Session 2 - Unit Tests

Presented by Guyllaume Cardinal for Cogeco Connexion

Let's just dive in!

Testing Pyramid

Testing Pyramid

The shape of the pyramid means something

Unit tests at the bottom because they're the foundation

 

More Unit tests than Integration tests

More Integration tests than Acceptance (E2E) tests

So, what's a unit test?

The smallest test you can do

Tests a single class (single behavior)

Any dependency is mocked

Tests behaviors so it does not break at every refactor

So, what's a unit test?

<?php
use PHPUnit\Framework\TestCase;

final class CalculatorTest extends TestCase
{
    public function testItCanAddNumbers()
    {
        $calculator = new Calculator();
        $this->assertGreaterThan(1, $calculator->add(1, 1));
    }

    public function testItCanSubstractNumbers()
    {
        $calculator = new Calculator();
        $this->assertLessThan(1, $calculator->substract(1, 1));
    }
}

And what's a Mock?

An object that mimics a real object in a controlled manner

Allows Unit tests to test only the unit under test

And what's a Mock?

<?php

class PokerGameTest extends PHPUnit_Framework_TestCase
{
    public function testItShouldAskTheDealerToDealItsCards()
    {
        $dealer = Phake::mock(DealerStrategy::class);
        $cards = Phake::mock(CardCollection::class);
        $players = Phake::mock(PlayerCollection::class);

        $pokerGame = new PokerGame($dealer, $cards, $players);
        $pokerGame->dealCards();

        Phake::verify($dealer)->deal(Phake::anyParameters());
    }
}

Tooling

Many tools exist

Use what you feel comfortable with

Today, we'll use

Phake

Onwards to coding!

Made with Slides.com