SlideShare a Scribd company logo
Unit Testing from
Setup to Deployment
Mark Niebergall
Thank You!
• Entrata - Venue, Food

• JetBrains - 1 free license

• Platform.sh - Zoom
https://analyze.co.za/wp-content/uploads/2018/12/441-1170x500.jpg
Objective
• Be familiar with how to setup PHPUnit

• Familiar with how to test existing code

• Know how to write unit tests using PHPUnit with
Prophecy

• Convince team and management to leverage automated
testing
Overview
• Bene
fi
ts of Unit Testing

• PHPUnit Setup

• Writing Unit Tests

• Testing Existing Code
Bene
fi
ts of Unit Testing
Bene
fi
ts of Unit Testing
public static function add($a, $b)
{
return $a + $b;
}
Bene
fi
ts of Unit Testing
public static function add($a, $b)
{
return $a + $b;
}
public function add(float ...$numbers): float
{
$return = 0;
foreach ($numbers as $value) {
$return = bcadd(
(string) $return,
(string) $value,
10
);
}
return (float) $return;
}
Bene
fi
ts of Unit Testing
http://www.ambysoft.com/artwork/comparingTechniques.jpg
Bene
fi
ts of Unit Testing
• Automated way to test code

- Regression Testing
Bene
fi
ts of Unit Testing
• Automated way to test code

- Continuous Integration

- Continuous Deployment
Bene
fi
ts of Unit Testing
• Automated way to test code

- Other ways to automatically test code beside functional
tests

‣ Behavioral tests (behat)

‣ phpspec (functional)

‣ Selenium (browser automation)

‣ Others?
Bene
fi
ts of Unit Testing
• Decrease bugs introduced with code

- Decreased time to deployment

- Better use of QA team time
Bene
fi
ts of Unit Testing
• Decrease bugs introduced with code

- High con
fi
dence in delivered code
Bene
fi
ts of Unit Testing
• Con
fi
dence when refactoring

- Tests covering code being refactored

- TDD

‣ Change tests

‣ Tests fail

‣ Change code

‣ Tests pass
PHPUnit Setup
PHPUnit Setup
• Install via composer

• Setup `phpunit.xml` for con
fi
guration (if needed)

• Run unit tests
PHPUnit Setup
• phpunit/phpunit

• phpspec/prophecy-phpunit

• fakerphp/faker
PHPUnit Setup
composer require --dev phpunit/phpunit
composer require --dev phpspec/prophecy-phpunit
composer require --dev fakerphp/faker
PHPUnit Setup
• File phpunit.xml

- PHPUnit con
fi
guration for that project

- Documentation: https://phpunit.readthedocs.io/en/9.5/
con
fi
guration.html



<?xml version="1.0" encoding="UTF-8"?>

<phpunit colors="true"
verbose="true"
bootstrap="./tests/Bootstrap.php">
<testsuite name="All Tests">
<directory>./tests</directory>
</testsuite>
</phpunit>
PHPUnit Setup
• Running PHPUnit



vendor/bin/phpunit tests/
PHPUnit 9.5.6 by Sebastian Bergmann and contributors.
Runtime: PHP 8.0.8
Con
fi
guration: /Users/mniebergall/projects/training/phpunit/
phpunit.xml
......... 9 / 9 (100%)
Time: 00:00.032, Memory: 6.00 MB
OK (9 tests, 12 assertions)
PHPUnit Setup
• Running PHPUnit

- Within PhpStorm
PHPUnit Setup
• Directory Structure

- PHP
fi
les in src/

‣ Ex: src/Math/Adder.php

- tests in tests/src/, ‘Test’ at end of
fi
lename

‣ Ex: tests/src/Math/AdderTest.php
Writing Unit Tests
Writing Unit Tests
public function add(float ...$numbers): float
{
$return = 0;
foreach ($numbers as $value) {
$return = bcadd(
(string) $return,
(string) $value,
10
);
}
return (float) $return;
}
Writing Unit Tests
use PHPUnitFrameworkTestCase;
class AdderTest extends TestCase
{
protected Adder $adder;
public function setUp(): void
{
$this->adder = new Adder();
}
public function testAdderWithSetup()
{
$sum = $this->adder->add(3, 7);
$this->assertSame(10.0, $sum);
}
Writing Unit Tests
public function testAdderThrowsExceptionWhenNotANumber()
{
$this->expectException(TypeError::class);
$adder = new Adder();
$adder->add(7, 'Can't add this');
}
Writing Unit Tests
public function testAdderAddsIntegers()
{
$adder = new Adder();
$sum = $adder->add(7, 3, 5, 5, 6, 4, 1, 9);
$this->assertSame(40.0, $sum);
}
public function testAdderAddsDecimals()
{
$adder = new Adder();
$sum = $adder->add(1.5, 0.5);
$this->assertSame(2.0, $sum);
}
Writing Unit Tests
/**
* @dataProvider dataProviderNumbers
*/
public function testAdderAddsNumbers(
float $expectedSum,
...$numbers
) {
$adder = new Adder();
$sum = $adder->add(...$numbers);
$this->assertSame($expectedSum, $sum);
}
public function dataProviderNumbers(): array
{
return [
[2, 1, 1],
[2, 1.5, 0.5],
];
}
Writing Unit Tests
• Test Coverage

- Percent of code covered by tests

- Not aiming for 100%

- No need to test language constructs
Writing Unit Tests
• Code should be self-contained

- No actual database connections

- No API calls should occur

- No external code should be called

‣ Use testing framework
Writing Unit Tests
• Assertions

$this->assertInstanceOf(Response::class, $response);
$this->assertEquals(200, $response->getStatusCode());
$this->assertSame(401, $responseActual->getStatusCode());
$this->assertTrue($dispatched);
$this->assertFalse($sent);
Writing Unit Tests
• Assertions

$this->expectException(RuntimeException::class);
$this->expectExceptionCode(403);
$this->expectExceptionMessage(‘Configuration not found.');
Writing Unit Tests
• Prophecy

- Mock objects

- Expected method calls

- Reveal object when injecting

use PHPUnitFrameworkTestCase;
use ProphecyPhpUnitProphecyTrait;
class RectangleTest extends TestCase
{
use ProphecyTrait;
Writing Unit Tests
• Prophecy

$adderMock = $this->prophesize(Adder::class);
$multiplierMock = $this->prophesize(Multiplier::class);
$adderMock->add($length, $width)
->shouldBeCalled()
->willReturn(10.34001);
$multiplierMock->multiply(2, 10.34001)
->shouldBeCalled()
->willReturn(20.68002);
$rectangle = new Rectangle(
$length,
$width,
$adderMock->reveal(),
$multiplierMock->reveal()
);
Writing Unit Tests
• Prophecy

$dbMock->fetchRow(Argument::any())
->shouldBeCalled()
->willReturn([]);
$asyncBusMock
->dispatch(
Argument::type(DoSomethingCmd::class),
Argument::type('array')
)
->shouldBeCalled()
->willReturn((new Envelope(new stdClass())));
Testing Existing Code
Testing Existing Code
• Problematic Patterns

- Long and complex functions
Testing Existing Code
• Problematic Patterns

- Missing Dependency Injection (DI)

‣ `new Thing();` in functions to be tested
Testing Existing Code
• Problematic Patterns

- exit and die

- print_r

- var_dump

- echo

- other outputs in-line
Testing Existing Code
• Problematic Patterns

- Database interactions

- Resources
Testing Existing Code
• Problematic Patterns

- Out of classes code execution

- Functional code
Testing Existing Code
• Helpful Patterns

- Unit testing promotes good code patterns
Testing Existing Code
• Helpful Patterns

- Dependency Injection

- Classes and functions focused on one thing

- Abstraction

- Interfaces

- Clean code
Testing Existing Code
• Helpful Patterns

- Code that is SOLID

‣ Single-responsibility: should be open for extension,
but closed for modi
fi
cation

‣ Open-closed: should be open for extension, but
closed for modi
fi
cation

‣ Liskov substitution: in PHP, use interface/abstract

‣ Interface segregation: Many client-speci
fi
c interfaces
are better than one general-purpose interface

‣ Dependency inversion: Depend upon abstractions,
[not] concretions
Testing Existing Code
• Helpful Patterns

- KISS
Testing Existing Code
• Test Coverage

- Percent of code covered by tests

- Not aiming for 100%

- No need to test language constructs

- Outputs report in various formats

- Uses Xdebug as driver
Testing Existing Code
class ShapeService
{
public function create(string $shape): int
{
$db = new Db();
return $db->insert('shape', ['shape' => $shape]);
}
public function smsArea(Rectangle $shape, string $toNumber): bool
{
$sms = new Sms([
'api_uri' => 'https://example.com/sms',
'api_key' => 'alkdjfoasifj0392lkdsjf',
]);
$sent = $sms->send($toNumber, 'Area is ' . $shape->area());
(new Logger())
->log('Sms sent to ' . $toNumber . ': Area is ' . $shape->area());
return $sent;
}
}
Testing Existing Code
class ShapeService
{
public function create(string $shape): int
{
$db = new Db();
return $db->insert('shape', ['shape' => $shape]);
}
public function smsArea(Rectangle $shape, string $toNumber): bool
{
$sms = new Sms([
'api_uri' => 'https://example.com/sms',
'api_key' => 'alkdjfoasifj0392lkdsjf',
]);
$sent = $sms->send($toNumber, 'Area is ' . $shape->area());
(new Logger())
->log('Sms sent to ' . $toNumber . ': Area is ' . $shape->area());
return $sent;
}
}
Testing Existing Code
class ShapeServiceCleanedUp
{
public function __construct(
protected Db $db,
protected Sms $sms
) {}
public function create(string $shape): int
{
return $this->db->insert('shape', ['shape' => $shape]);
}
public function smsArea(ShapeInterface $shape, string $toNumber): bool
{
$area = $shape->area();
return $this->sms->send($toNumber, 'Area is ' . $area);
}
Testing Existing Code
use ProphecyTrait;
protected Generator $faker;
public function setUp(): void
{
$this->faker = Factory::create();
}
public function testCreate()
{
$dbMock = $this->prophesize(Db::class);
$smsMock = $this->prophesize(Sms::class);
$shape = $this->faker->word;
$dbMock->insert('shape', ['shape' => $shape])
->shouldBeCalled()
->willReturn(1);
$shapeServiceCleanedUp = new ShapeServiceCleanedUp(
$dbMock->reveal(),
$smsMock->reveal()
);
$shapeServiceCleanedUp->create($shape);
}
Testing Existing Code
public function testSmsArea()
{
$dbMock = $this->prophesize(Db::class);
$smsMock = $this->prophesize(Sms::class);
$shapeMock = $this->prophesize(ShapeInterface::class);
$area = $this->faker->randomFloat();
$shapeMock->area()
->shouldBeCalled()
->willReturn($area);
$toNumber = $this->faker->phoneNumber;
$smsMock->send($toNumber, 'Area is ' . $area)
->shouldBeCalled()
->willReturn(1);
$shapeServiceCleanedUp = new ShapeServiceCleanedUp(
$dbMock->reveal(),
$smsMock->reveal()
);
$shapeServiceCleanedUp->smsArea(
$shapeMock->reveal(),
$toNumber
);
}
Live Examples
Discussion Items
• Convincing Teammates

• Convincing Management
Discussion Items
• Does unit testing slow development down?
Discussion Items
• “I don’t see the bene
fi
t of unit testing”
Discussion Items
• Unit tests for legacy code
Discussion Items
• Other?
Review
• Bene
fi
ts of Unit Testing

• PHPUnit Setup

• Writing Unit Tests

• Testing Existing Code
Unit Testing from Setup to Deployment
• Questions?
Mark Niebergall @mbniebergall
• PHP since 2005

• Masters degree in MIS

• Senior Software Engineer

• Drug screening project

• Utah PHP Co-Organizer

• CSSLP, SSCP Certi
fi
ed and SME

• Endurance sports, outdoors
References
• https://analyze.co.za/wp-content/uploads/
2018/12/441-1170x500.jpg

• http://www.ambysoft.com/artwork/
comparingTechniques.jpg

• https://en.wikipedia.org/wiki/SOLID

More Related Content

What's hot

Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
Alexander Loechel
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
Arulalan T
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
David Wheeler
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Harry Potter
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
gturnquist
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
Rabble .
 
Vagrant+Rouster at salesforce.com
Vagrant+Rouster at salesforce.comVagrant+Rouster at salesforce.com
Vagrant+Rouster at salesforce.com
chorankates
 
Test
TestTest
Test
Eddie Kao
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Samyak Bhalerao
 
Auto Deploy Deep Dive – vBrownBag Style
Auto Deploy Deep Dive – vBrownBag StyleAuto Deploy Deep Dive – vBrownBag Style
Auto Deploy Deep Dive – vBrownBag Style
Robert Nelson
 
Presentation_C++UnitTest
Presentation_C++UnitTestPresentation_C++UnitTest
Presentation_C++UnitTestRaihan Masud
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
Timo Stollenwerk
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
dn
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
James Fuller
 
Puppet evolutions
Puppet evolutionsPuppet evolutions
Puppet evolutions
Alessandro Franceschi
 
Laravel 5.5 dev
Laravel 5.5 devLaravel 5.5 dev
Laravel 5.5 dev
RocketRoute
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
Arthur Freyman
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 

What's hot (20)

Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Vagrant+Rouster at salesforce.com
Vagrant+Rouster at salesforce.comVagrant+Rouster at salesforce.com
Vagrant+Rouster at salesforce.com
 
Test
TestTest
Test
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
Auto Deploy Deep Dive – vBrownBag Style
Auto Deploy Deep Dive – vBrownBag StyleAuto Deploy Deep Dive – vBrownBag Style
Auto Deploy Deep Dive – vBrownBag Style
 
Presentation_C++UnitTest
Presentation_C++UnitTestPresentation_C++UnitTest
Presentation_C++UnitTest
 
Pyunit
PyunitPyunit
Pyunit
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Puppet evolutions
Puppet evolutionsPuppet evolutions
Puppet evolutions
 
Laravel 5.5 dev
Laravel 5.5 devLaravel 5.5 dev
Laravel 5.5 dev
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 

Similar to Unit Testing from Setup to Deployment

Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
Mark Niebergall
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
Mark Niebergall
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
Michelangelo van Dam
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207patter
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
Eric Hogue
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublin
Michelangelo van Dam
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
Mindfire Solutions
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
Anatoliy Okhotnikov
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
Thanh Robi
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
Michelangelo van Dam
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
Alan Pinstein
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
Michelangelo van Dam
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
New Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian BergmannNew Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian Bergmanndpc
 

Similar to Unit Testing from Setup to Deployment (20)

Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublin
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Testing untestable code - DPC10
Testing untestable code - DPC10Testing untestable code - DPC10
Testing untestable code - DPC10
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
New Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian BergmannNew Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian Bergmann
 

More from Mark Niebergall

Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023
Mark Niebergall
 
Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023
Mark Niebergall
 
Developing SOLID Code
Developing SOLID CodeDeveloping SOLID Code
Developing SOLID Code
Mark Niebergall
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
Mark Niebergall
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
Mark Niebergall
 
Hacking with PHP
Hacking with PHPHacking with PHP
Hacking with PHP
Mark Niebergall
 
Relational Database Design Bootcamp
Relational Database Design BootcampRelational Database Design Bootcamp
Relational Database Design Bootcamp
Mark Niebergall
 
Starting Out With PHP
Starting Out With PHPStarting Out With PHP
Starting Out With PHP
Mark Niebergall
 
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Mark Niebergall
 
Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018
Mark Niebergall
 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
Mark Niebergall
 
Defensive Coding Crash Course Tutorial
Defensive Coding Crash Course TutorialDefensive Coding Crash Course Tutorial
Defensive Coding Crash Course Tutorial
Mark Niebergall
 
Inheritance: Vertical or Horizontal
Inheritance: Vertical or HorizontalInheritance: Vertical or Horizontal
Inheritance: Vertical or Horizontal
Mark Niebergall
 
Cybersecurity State of the Union
Cybersecurity State of the UnionCybersecurity State of the Union
Cybersecurity State of the Union
Mark Niebergall
 
Cryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 WorkshopCryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 Workshop
Mark Niebergall
 
Defensive Coding Crash Course - ZendCon 2017
Defensive Coding Crash Course - ZendCon 2017Defensive Coding Crash Course - ZendCon 2017
Defensive Coding Crash Course - ZendCon 2017
Mark Niebergall
 
Leveraging Composer in Existing Projects
Leveraging Composer in Existing ProjectsLeveraging Composer in Existing Projects
Leveraging Composer in Existing Projects
Mark Niebergall
 
Defensive Coding Crash Course
Defensive Coding Crash CourseDefensive Coding Crash Course
Defensive Coding Crash Course
Mark Niebergall
 
Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!
Mark Niebergall
 
Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)
Mark Niebergall
 

More from Mark Niebergall (20)

Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023
 
Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023
 
Developing SOLID Code
Developing SOLID CodeDeveloping SOLID Code
Developing SOLID Code
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
 
Hacking with PHP
Hacking with PHPHacking with PHP
Hacking with PHP
 
Relational Database Design Bootcamp
Relational Database Design BootcampRelational Database Design Bootcamp
Relational Database Design Bootcamp
 
Starting Out With PHP
Starting Out With PHPStarting Out With PHP
Starting Out With PHP
 
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
 
Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018
 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
 
Defensive Coding Crash Course Tutorial
Defensive Coding Crash Course TutorialDefensive Coding Crash Course Tutorial
Defensive Coding Crash Course Tutorial
 
Inheritance: Vertical or Horizontal
Inheritance: Vertical or HorizontalInheritance: Vertical or Horizontal
Inheritance: Vertical or Horizontal
 
Cybersecurity State of the Union
Cybersecurity State of the UnionCybersecurity State of the Union
Cybersecurity State of the Union
 
Cryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 WorkshopCryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 Workshop
 
Defensive Coding Crash Course - ZendCon 2017
Defensive Coding Crash Course - ZendCon 2017Defensive Coding Crash Course - ZendCon 2017
Defensive Coding Crash Course - ZendCon 2017
 
Leveraging Composer in Existing Projects
Leveraging Composer in Existing ProjectsLeveraging Composer in Existing Projects
Leveraging Composer in Existing Projects
 
Defensive Coding Crash Course
Defensive Coding Crash CourseDefensive Coding Crash Course
Defensive Coding Crash Course
 
Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!
 
Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)
 

Recently uploaded

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 

Recently uploaded (20)

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

Unit Testing from Setup to Deployment

  • 1. Unit Testing from Setup to Deployment Mark Niebergall
  • 2. Thank You! • Entrata - Venue, Food • JetBrains - 1 free license • Platform.sh - Zoom
  • 4. Objective • Be familiar with how to setup PHPUnit • Familiar with how to test existing code • Know how to write unit tests using PHPUnit with Prophecy • Convince team and management to leverage automated testing
  • 5. Overview • Bene fi ts of Unit Testing • PHPUnit Setup • Writing Unit Tests • Testing Existing Code
  • 7. Bene fi ts of Unit Testing public static function add($a, $b) { return $a + $b; }
  • 8. Bene fi ts of Unit Testing public static function add($a, $b) { return $a + $b; } public function add(float ...$numbers): float { $return = 0; foreach ($numbers as $value) { $return = bcadd( (string) $return, (string) $value, 10 ); } return (float) $return; }
  • 9. Bene fi ts of Unit Testing http://www.ambysoft.com/artwork/comparingTechniques.jpg
  • 10. Bene fi ts of Unit Testing • Automated way to test code - Regression Testing
  • 11. Bene fi ts of Unit Testing • Automated way to test code - Continuous Integration - Continuous Deployment
  • 12. Bene fi ts of Unit Testing • Automated way to test code - Other ways to automatically test code beside functional tests ‣ Behavioral tests (behat) ‣ phpspec (functional) ‣ Selenium (browser automation) ‣ Others?
  • 13. Bene fi ts of Unit Testing • Decrease bugs introduced with code - Decreased time to deployment - Better use of QA team time
  • 14. Bene fi ts of Unit Testing • Decrease bugs introduced with code - High con fi dence in delivered code
  • 15. Bene fi ts of Unit Testing • Con fi dence when refactoring - Tests covering code being refactored - TDD ‣ Change tests ‣ Tests fail ‣ Change code ‣ Tests pass
  • 17. PHPUnit Setup • Install via composer • Setup `phpunit.xml` for con fi guration (if needed) • Run unit tests
  • 18. PHPUnit Setup • phpunit/phpunit • phpspec/prophecy-phpunit • fakerphp/faker
  • 19. PHPUnit Setup composer require --dev phpunit/phpunit composer require --dev phpspec/prophecy-phpunit composer require --dev fakerphp/faker
  • 20. PHPUnit Setup • File phpunit.xml - PHPUnit con fi guration for that project - Documentation: https://phpunit.readthedocs.io/en/9.5/ con fi guration.html 
 <?xml version="1.0" encoding="UTF-8"?> <phpunit colors="true" verbose="true" bootstrap="./tests/Bootstrap.php"> <testsuite name="All Tests"> <directory>./tests</directory> </testsuite> </phpunit>
  • 21. PHPUnit Setup • Running PHPUnit 
 vendor/bin/phpunit tests/ PHPUnit 9.5.6 by Sebastian Bergmann and contributors. Runtime: PHP 8.0.8 Con fi guration: /Users/mniebergall/projects/training/phpunit/ phpunit.xml ......... 9 / 9 (100%) Time: 00:00.032, Memory: 6.00 MB OK (9 tests, 12 assertions)
  • 22. PHPUnit Setup • Running PHPUnit - Within PhpStorm
  • 23. PHPUnit Setup • Directory Structure - PHP fi les in src/ ‣ Ex: src/Math/Adder.php - tests in tests/src/, ‘Test’ at end of fi lename ‣ Ex: tests/src/Math/AdderTest.php
  • 25. Writing Unit Tests public function add(float ...$numbers): float { $return = 0; foreach ($numbers as $value) { $return = bcadd( (string) $return, (string) $value, 10 ); } return (float) $return; }
  • 26. Writing Unit Tests use PHPUnitFrameworkTestCase; class AdderTest extends TestCase { protected Adder $adder; public function setUp(): void { $this->adder = new Adder(); } public function testAdderWithSetup() { $sum = $this->adder->add(3, 7); $this->assertSame(10.0, $sum); }
  • 27. Writing Unit Tests public function testAdderThrowsExceptionWhenNotANumber() { $this->expectException(TypeError::class); $adder = new Adder(); $adder->add(7, 'Can't add this'); }
  • 28. Writing Unit Tests public function testAdderAddsIntegers() { $adder = new Adder(); $sum = $adder->add(7, 3, 5, 5, 6, 4, 1, 9); $this->assertSame(40.0, $sum); } public function testAdderAddsDecimals() { $adder = new Adder(); $sum = $adder->add(1.5, 0.5); $this->assertSame(2.0, $sum); }
  • 29. Writing Unit Tests /** * @dataProvider dataProviderNumbers */ public function testAdderAddsNumbers( float $expectedSum, ...$numbers ) { $adder = new Adder(); $sum = $adder->add(...$numbers); $this->assertSame($expectedSum, $sum); } public function dataProviderNumbers(): array { return [ [2, 1, 1], [2, 1.5, 0.5], ]; }
  • 30. Writing Unit Tests • Test Coverage - Percent of code covered by tests - Not aiming for 100% - No need to test language constructs
  • 31. Writing Unit Tests • Code should be self-contained - No actual database connections - No API calls should occur - No external code should be called ‣ Use testing framework
  • 32. Writing Unit Tests • Assertions $this->assertInstanceOf(Response::class, $response); $this->assertEquals(200, $response->getStatusCode()); $this->assertSame(401, $responseActual->getStatusCode()); $this->assertTrue($dispatched); $this->assertFalse($sent);
  • 33. Writing Unit Tests • Assertions $this->expectException(RuntimeException::class); $this->expectExceptionCode(403); $this->expectExceptionMessage(‘Configuration not found.');
  • 34. Writing Unit Tests • Prophecy - Mock objects - Expected method calls - Reveal object when injecting use PHPUnitFrameworkTestCase; use ProphecyPhpUnitProphecyTrait; class RectangleTest extends TestCase { use ProphecyTrait;
  • 35. Writing Unit Tests • Prophecy $adderMock = $this->prophesize(Adder::class); $multiplierMock = $this->prophesize(Multiplier::class); $adderMock->add($length, $width) ->shouldBeCalled() ->willReturn(10.34001); $multiplierMock->multiply(2, 10.34001) ->shouldBeCalled() ->willReturn(20.68002); $rectangle = new Rectangle( $length, $width, $adderMock->reveal(), $multiplierMock->reveal() );
  • 36. Writing Unit Tests • Prophecy $dbMock->fetchRow(Argument::any()) ->shouldBeCalled() ->willReturn([]); $asyncBusMock ->dispatch( Argument::type(DoSomethingCmd::class), Argument::type('array') ) ->shouldBeCalled() ->willReturn((new Envelope(new stdClass())));
  • 38. Testing Existing Code • Problematic Patterns - Long and complex functions
  • 39. Testing Existing Code • Problematic Patterns - Missing Dependency Injection (DI) ‣ `new Thing();` in functions to be tested
  • 40. Testing Existing Code • Problematic Patterns - exit and die - print_r - var_dump - echo - other outputs in-line
  • 41. Testing Existing Code • Problematic Patterns - Database interactions - Resources
  • 42. Testing Existing Code • Problematic Patterns - Out of classes code execution - Functional code
  • 43. Testing Existing Code • Helpful Patterns - Unit testing promotes good code patterns
  • 44. Testing Existing Code • Helpful Patterns - Dependency Injection - Classes and functions focused on one thing - Abstraction - Interfaces - Clean code
  • 45. Testing Existing Code • Helpful Patterns - Code that is SOLID ‣ Single-responsibility: should be open for extension, but closed for modi fi cation ‣ Open-closed: should be open for extension, but closed for modi fi cation ‣ Liskov substitution: in PHP, use interface/abstract ‣ Interface segregation: Many client-speci fi c interfaces are better than one general-purpose interface ‣ Dependency inversion: Depend upon abstractions, [not] concretions
  • 46. Testing Existing Code • Helpful Patterns - KISS
  • 47. Testing Existing Code • Test Coverage - Percent of code covered by tests - Not aiming for 100% - No need to test language constructs - Outputs report in various formats - Uses Xdebug as driver
  • 48. Testing Existing Code class ShapeService { public function create(string $shape): int { $db = new Db(); return $db->insert('shape', ['shape' => $shape]); } public function smsArea(Rectangle $shape, string $toNumber): bool { $sms = new Sms([ 'api_uri' => 'https://example.com/sms', 'api_key' => 'alkdjfoasifj0392lkdsjf', ]); $sent = $sms->send($toNumber, 'Area is ' . $shape->area()); (new Logger()) ->log('Sms sent to ' . $toNumber . ': Area is ' . $shape->area()); return $sent; } }
  • 49. Testing Existing Code class ShapeService { public function create(string $shape): int { $db = new Db(); return $db->insert('shape', ['shape' => $shape]); } public function smsArea(Rectangle $shape, string $toNumber): bool { $sms = new Sms([ 'api_uri' => 'https://example.com/sms', 'api_key' => 'alkdjfoasifj0392lkdsjf', ]); $sent = $sms->send($toNumber, 'Area is ' . $shape->area()); (new Logger()) ->log('Sms sent to ' . $toNumber . ': Area is ' . $shape->area()); return $sent; } }
  • 50. Testing Existing Code class ShapeServiceCleanedUp { public function __construct( protected Db $db, protected Sms $sms ) {} public function create(string $shape): int { return $this->db->insert('shape', ['shape' => $shape]); } public function smsArea(ShapeInterface $shape, string $toNumber): bool { $area = $shape->area(); return $this->sms->send($toNumber, 'Area is ' . $area); }
  • 51. Testing Existing Code use ProphecyTrait; protected Generator $faker; public function setUp(): void { $this->faker = Factory::create(); } public function testCreate() { $dbMock = $this->prophesize(Db::class); $smsMock = $this->prophesize(Sms::class); $shape = $this->faker->word; $dbMock->insert('shape', ['shape' => $shape]) ->shouldBeCalled() ->willReturn(1); $shapeServiceCleanedUp = new ShapeServiceCleanedUp( $dbMock->reveal(), $smsMock->reveal() ); $shapeServiceCleanedUp->create($shape); }
  • 52. Testing Existing Code public function testSmsArea() { $dbMock = $this->prophesize(Db::class); $smsMock = $this->prophesize(Sms::class); $shapeMock = $this->prophesize(ShapeInterface::class); $area = $this->faker->randomFloat(); $shapeMock->area() ->shouldBeCalled() ->willReturn($area); $toNumber = $this->faker->phoneNumber; $smsMock->send($toNumber, 'Area is ' . $area) ->shouldBeCalled() ->willReturn(1); $shapeServiceCleanedUp = new ShapeServiceCleanedUp( $dbMock->reveal(), $smsMock->reveal() ); $shapeServiceCleanedUp->smsArea( $shapeMock->reveal(), $toNumber ); }
  • 54. Discussion Items • Convincing Teammates • Convincing Management
  • 55. Discussion Items • Does unit testing slow development down?
  • 56. Discussion Items • “I don’t see the bene fi t of unit testing”
  • 57. Discussion Items • Unit tests for legacy code
  • 59. Review • Bene fi ts of Unit Testing • PHPUnit Setup • Writing Unit Tests • Testing Existing Code
  • 60. Unit Testing from Setup to Deployment • Questions?
  • 61. Mark Niebergall @mbniebergall • PHP since 2005 • Masters degree in MIS • Senior Software Engineer • Drug screening project • Utah PHP Co-Organizer • CSSLP, SSCP Certi fi ed and SME • Endurance sports, outdoors