Upload
sudar-muthu
View
442
Download
0
Embed Size (px)
Citation preview
Unit Testing PHP codeSudar Muthu
http://sudarmuthu.com https://github.com/sudar
Me
• Programming in PHP for more than a decade
• Programming in WordPress for 8 years
• Big fan of automating process and workflows
• Occasionally contribute to open source projects
2
What about you?
• What is your typical development environment looks like?
• What is your experience with PHP?
• What is your experience with Unit Testing?
• What are your expectations out of this talk?
3
Is there something wrong?class Sample { protected $value;
public function initialize($value) { $this->value = $value; }
public function execute() { if (!$this->value) { throw new Exception("value not set"); } return $value * 10; // business logic }}
$sample = new Sample;$sample->execute();
4
Finding bugs is not easy
5
Write Tests
6
Write Tests
7
It sounds obvious but getting started is the hardest part!
Different types of Testing
• Functionality testing
• Integration testing
• Unit testing
8
Different types of Testing
• Functionality testing
• Integration testing
• Unit testing
9
Briefly
• What is PHPUnit?
• Installing PHPUnit
• Setting up folder structure
• phpunit.xml
10
Test classes, not methods
• Unit testing, is about testing the observable behaviours of a class!
• Observable from the outside! Nobody cares about the internal state of a class if it never changes the outcome of a method call.
• Don’t test getters and setters, unless they have custom validation
Three steps in test cases
• setup
• act
• verify
Demo
13
Writing our first test case public function test_execute_works_with_initialize() { // setup $sample = new Sample();
// act $sample->initialize(10); $return = $sample->execute();
// verify $this->assertEquals(100, $return); }
Testing Exception /** * @expectedException Exception */ public function test_execute_needs_initialize() { // setup $sample = new Sample();
// act $sample->execute();
// verify // that it throws and exception }
Let’s add more tests
• Testing decimals
• Testing with negative values
• Testing it work with zero
Why use mocks?
• Isolate the test class from its dependencies.
• Test functionality that calls external services.
• Test functionality that depends on class internals.
Some PHPUnit Tips• Have a fast test suite
• Use Continuous Integration
• Use Composer
• Enable code coverage in reports
• phpunit.xml.dist vs phpunit.xml
• Use specific assertions
Thank You
19
@sudarmuthu http://sudarmuthu.com
https://github.com/sudar