Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Unit testing in php

1,536 views

Published on

Slides from my talk about "Unit Testing in PHP"

Published in: Technology
  • Be the first to comment

Unit testing in php

  1. 1. Unit Testing PHP code Sudar Muthu http://sudarmuthu.com https://github.com/sudar
  2. 2. 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
  3. 3. 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
  4. 4. 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
  5. 5. Finding bugs is not easy 5
  6. 6. Write Tests 6
  7. 7. Write Tests 7 It sounds obvious but getting started is the hardest part!
  8. 8. Different types of Testing • Functionality testing • Integration testing • Unit testing 8
  9. 9. Different types of Testing • Functionality testing • Integration testing • Unit testing 9
  10. 10. Briefly • What is PHPUnit? • Installing PHPUnit • Setting up folder structure • phpunit.xml 10
  11. 11. 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
  12. 12. Three steps in test cases • setup • act • verify
  13. 13. Demo 13
  14. 14. 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); }
  15. 15. Testing Exception /** * @expectedException Exception */ public function test_execute_needs_initialize() { // setup $sample = new Sample(); // act $sample->execute(); // verify // that it throws and exception }
  16. 16. Let’s add more tests • Testing decimals • Testing with negative values • Testing it work with zero
  17. 17. Why use mocks? • Isolate the test class from its dependencies. • Test functionality that calls external services. • Test functionality that depends on class internals.
  18. 18. 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
  19. 19. Thank You 19 @sudarmuthu http://sudarmuthu.com https://github.com/sudar

×