PHP Unit Testing

Table of Contents

  • What is Unit Testing
  • What is a Unit?
  • What is makes Unit Testing difficult?
  • How is a Unit Test Build?
  • What to Mock and what to Stub?
  • What to Expect or Assert?

What is Unit Testing

  • Unit Testing is testing a unit of code in isolation
  • Unit Testing is usually done before the code is committed
  • Unit Testing is usually done on the developer's machine and on the CI server

What is a Unit?

  • A unit is usually a class or a function
  • A unit is a small part of the codebase
  • A unit is a part of the codebase that can be tested in isolation

What is makes Unit Testing difficult?

  • When the code is not using dependency injection
  • When the code is using static functions
  • When the code is using built-in functions
  • When the code is using global state

How is a Unit Test Build?

Theory

  • Describe...
  • When...
  • Action...
  • Then...

How is a Unit Test Build?

Example

class CalculatorTest extends TestCase
{
    /** @test */
    public function whenTwoNumbersAreProvidedTheSumIsCalculated()
    {
        $calculator = new Calculator();
        $result = $calculator->add(1, 2);
        self::assertEquals(3, $result);
    }
}

What to Mock and what to Stub?

  • Mock the relevant dependencies of the unit
  • Do not mock pure logic-less Objects (DTOs, Entities, Value Objects)
  • Stub any dependency that is not relevant for the test
  • Do not mock the unit you are testing

What to Expect or Assert?

  • Assert the result of the unit
  • Expect calls on Mocks
  • Assert the state of the unit for logic-less Objects (DTOs, Entities, Value Objects)
Thank you for your time!