0
Test Driven Development with
PHPUnit
By: Kshirodra Meher
Software Engineer
Mindfire Solutions
Contents

Who am I ?

What & Why to do Testing ?

What is Unit testing ?

PHPUnit

Starting with PHPUnit

PHPUnit Ex...
Who am I ?
Kshirodra Meher
PHP Developer,
Mindfire Solutions
(Aug-2011 to Present)
What & Why to do Testing ?

Testing : revealing a person's capabilities by putting them under strain;
challenging. :P

S...
What is Unit Testing ?

Unit : The smallest testable code of an application

Test : Code that checks code on

If you do...
Simple Test

Comparable to JUnit/PHPUnit

Created by Marcus Baker

Popular for testing web
pages at browser level
PHPUnit

PHPUnit is a programmer oriented testing framework for PHP

Part of xUnit family (JUnit, SUnit..)

Created By ...
Starting with PHPUnit

PHPUnit can be installed using PEAR installer

Commands to install :
#pear config-set auto_discov...
Writing Tests for PHPUnit

The tests for a class Class go into a class ClassTest

ClassTest inherits(most of the time) f...
Lets do 'Hello World'
<?php
class HelloWorld {
public $helloWorld;
public function __construct($string = ‘Hello
World!’) {...
Test HelloWorld Class
require_once 'HelloWorld.php';
class HelloWorldTest extends PHPUnit_Framework_TestCase {
public func...
Testing HelloWorld
#phpunit HelloWorldTest.php
PHPUnit 4.0.7 by Sebastian Bergmann.
..
Time: 70 ms, Memory: 3.75Mb
OK (2 t...
PHPUnit Test Results Details

. - Printed when the test succeeds

F - Printed when an assertion fails while running the ...
Test Dependencies

PHPUnit supports the declaration of the explicit dependencies between test
methods. Such dependencies ...
Data Provider

Test method can accept arbitrary arguments. These arguments are to be
provided by a data provider methods....
Testing Error & Exceptions

PHPUnit converts PHP errors, warning, and notices that are triggered during
the execution of ...
Test Output

Sometimes you want to assert that the execution of a method, for instance,
generates an expected output via ...
Assertions
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOn...
Assertions
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMat...
Fixtures

Is a known state of an application

Need to be set up at the start of the test

Need to be torn down at the e...
Database Testing

PHPUnit Database Extension

Can be installed by :
# pear install phpunit/DbUnit

Currently supported ...
Database Testing

Four stages of database testing
- Setup fixture
- Exercise System Under Test
- Verify Outcome
- Teardow...
Incomplete & Skipped Test

Interface PHP_Unit_Framework_IncompleteTest
- markTestImcomplete()
- markTestIncomplete(string...
Test Doubles

Introduced By : Gerard Meszaros

Replace a System Under Test (SUT) for the purpose of testing

Stubs
- Us...
Testing Practices

Development
- All unit tests run correctly.
- The code communicates its design principles.
- The code ...
Code Coverage Analysis

How do you find code that is not yet tested or, in other words, not yet
covered by a test?

How ...
Skeleton Generator & Selenium

PHPUnit Skeleton Generator is a tool that can generate skeleton test
classes from producti...
Sources

http://phpunit.de/manual/current/en/index.html

https://github.com/sebastianbergmann/phpunit
Thank You
Test Driven Development with PHPUnit
Upcoming SlideShare
Loading in...5
×

Test Driven Development with PHPUnit

679

Published on

This presentation would help learn how to install, integrate, write automated test script with PHPUnit.Would also involve looking into different example and execute them.

Published in: Software, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
679
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Test Driven Development with PHPUnit"

  1. 1. Test Driven Development with PHPUnit By: Kshirodra Meher Software Engineer Mindfire Solutions
  2. 2. Contents  Who am I ?  What & Why to do Testing ?  What is Unit testing ?  PHPUnit  Starting with PHPUnit  PHPUnit Example  Test Dependencies  Data Provider  Testing Error & Exceptions  Test Output Assertion Fixtures Database Testing Incomplete & Skipped Test Test Doubles Testing Practice Code Coverage Analysis Skeleton Generator & Selenium Sources & Questions?
  3. 3. Who am I ? Kshirodra Meher PHP Developer, Mindfire Solutions (Aug-2011 to Present)
  4. 4. What & Why to do Testing ?  Testing : revealing a person's capabilities by putting them under strain; challenging. :P  S/W Testing : Software testing is an investigation conducted to provide stakeholders with information about the quality of the product or service under test.  Why S/W Testing : - Meet the requirements that guided its design and development - Expected Results / Unexpected Failure  Software never was perfect and won’t get perfect. But is that a license to create garbage? The missing ingredient is our reluctance to quantify quality. – Boris Beizer
  5. 5. What is Unit Testing ?  Unit : The smallest testable code of an application  Test : Code that checks code on  If you don’t like unit testing your product, most likely your customers won’t like to test it either.  Benefits : - Changing/maintaining code - Fixing cost is low - Faster development etc etc .
  6. 6. Simple Test  Comparable to JUnit/PHPUnit  Created by Marcus Baker  Popular for testing web pages at browser level
  7. 7. PHPUnit  PHPUnit is a programmer oriented testing framework for PHP  Part of xUnit family (JUnit, SUnit..)  Created By : Sebastian Bergmann  Integrated in most IDE : - Eclipse, Netbeans, Zend Studio, PHPStorm  Integrated/Supported by : - Zend Framework, Cake, Symfony
  8. 8. Starting with PHPUnit  PHPUnit can be installed using PEAR installer  Commands to install : #pear config-set auto_discover 1 #pear install pear.phpunit.de/PHPUnit
  9. 9. Writing Tests for PHPUnit  The tests for a class Class go into a class ClassTest  ClassTest inherits(most of the time) from PHPUnit_Framework_TestCase  The tests are public methods that are named test*.  Inside the test methods, assertions methods such as assertEquals() are used to assert that an actual value matches an expected value.
  10. 10. Lets do 'Hello World' <?php class HelloWorld { public $helloWorld; public function __construct($string = ‘Hello World!’) { $this->helloWorld = $string; } public function sayHello() { return $this->helloWorld; } }
  11. 11. Test HelloWorld Class require_once 'HelloWorld.php'; class HelloWorldTest extends PHPUnit_Framework_TestCase { public function test__construct() { $hw = new HelloWorld(); $this->assertInstanceOf('HelloWorld', $hw); } public function testSayHello() { $hw = new HelloWorld(); $string = $hw->sayHello(); $this->assertEquals('Hello World!', $string); } }
  12. 12. Testing HelloWorld #phpunit HelloWorldTest.php PHPUnit 4.0.7 by Sebastian Bergmann. .. Time: 70 ms, Memory: 3.75Mb OK (2 tests, 2 assertions)
  13. 13. PHPUnit Test Results Details  . - Printed when the test succeeds  F - Printed when an assertion fails while running the test method  E - Printed when an error occurs while running the test method  S - Printed when the test has been skipped  I - Printed when the test is marked as being incomplete or not yet implemented PHPUnit distinguishes between failures and errors. A failure is a violated PHPUnit assertion such as a failing assertEquals() call. An error is an unexpected exception or a PHP error. Sometimes this distinction proves useful since errors tend to be easier to fix than failures.
  14. 14. Test Dependencies  PHPUnit supports the declaration of the explicit dependencies between test methods. Such dependencies do not define the order in which the test methods are to be executed but they allow the returning of an instance of the test fixture by a producer and passing it to the dependent consumers.  A producer is a test method that yields its unit under test as return values.  A consumer is a test method that depends on one or more producers and their return values.  Annotated by @depends
  15. 15. Data Provider  Test method can accept arbitrary arguments. These arguments are to be provided by a data provider methods. - Array - Objects (that implements iterator)  Multiple arguments  Annotated by @dataProvider
  16. 16. Testing Error & Exceptions  PHPUnit converts PHP errors, warning, and notices that are triggered during the execution of a test to an exception. Using these exceptions, you can, for instance, expect a test to trigger a PHP error  Tests whether an exception is thrown inside the tested code.  Annotated by @expectedExceptions
  17. 17. Test Output  Sometimes you want to assert that the execution of a method, for instance, generates an expected output via echo or print. class OutputTest extends PHPUnit_Framework_TestCase { public function testExpectFooActualFoo() { $this->expectOutputString('foo'); print 'foo'; } public function testExpectBarActualBaz() { $this->expectOutputString('bar'); print 'baz'; } }
  18. 18. Assertions assertArrayHasKey() assertClassHasAttribute() assertClassHasStaticAttribute() assertContains() assertContainsOnly() assertContainsOnlyInstancesOf() assertCount() assertEmpty() assertEqualXMLStructure() assertEquals() assertFalse() assertFileEquals() assertFileExists() assertGreaterThan() assertGreaterThanOrEqual() assertInstanceOf() assertInternalType() assertJsonFileEqualsJsonFile() assertJsonStringEqualsJsonFile() assertJsonStringEqualsJsonString()
  19. 19. Assertions assertLessThan() assertLessThanOrEqual() assertNull() assertObjectHasAttribute() assertRegExp() assertStringMatchesFormat() assertStringMatchesFormatFile() assertSame() assertSelectCount() assertSelectEquals() assertSelectRegExp() assertStringEndsWith() assertStringEqualsFile() assertStringStartsWith() assertTag() assertThat() assertTrue() assertXmlFileEqualsXmlFile() assertXmlStringEqualsXmlFile() assertXmlStringEqualsXmlString()
  20. 20. Fixtures  Is a known state of an application  Need to be set up at the start of the test  Need to be torn down at the end of the test  Share states over the test methods  setUp() is where you create objects against which you will test  tearDown() is where you clean up the objects against which you tested  More setUp() then tearDown()  The setUpBeforeClass() and tearDownAfterClass() template methods are called before the first test of the test case class is run and after the last test of the case class is run, respectively
  21. 21. Database Testing  PHPUnit Database Extension  Can be installed by : # pear install phpunit/DbUnit  Currently supported database : - MySQL - PostgreSQL - Oracle - SQLite  Has access to other database systems such as IBM DB2 / Microsoft SQL Server through Zend Framework or Doctrine 2 integration
  22. 22. Database Testing  Four stages of database testing - Setup fixture - Exercise System Under Test - Verify Outcome - Teardown (1. Clean-Up Database, 2. Set up fixture, 3–5. Run Test, Verify outcome and Teardown)  Must implement - getConnection() : Returns a database connection wrapper - getDataSet() : Returns the dataset to seed the database with
  23. 23. Incomplete & Skipped Test  Interface PHP_Unit_Framework_IncompleteTest - markTestImcomplete() - markTestIncomplete(string $msg)  Skipped Test - markTestSkipped() - markTestIncomplete(string $msg)  Skipped @requires
  24. 24. Test Doubles  Introduced By : Gerard Meszaros  Replace a System Under Test (SUT) for the purpose of testing  Stubs - Used for providing the tested code with "indirect input"  Mocks - Used for verifying "indirect output" of the tested code, by first defining the expectations before the tested code is executed
  25. 25. Testing Practices  Development - All unit tests run correctly. - The code communicates its design principles. - The code contains no redundancies. - The code contains the minimal number of classes and methods.  Debugging - Verify that you can reproduce the defect. - Find the smallest-scale demonstration of the defect in the code. - Write an automated test that fails now but will succeed when the defect is fixed. - Fix the defect.
  26. 26. Code Coverage Analysis  How do you find code that is not yet tested or, in other words, not yet covered by a test?  How do you measure testing completeness?  phpunit --coverage-html ./report BankAccountTest
  27. 27. Skeleton Generator & Selenium  PHPUnit Skeleton Generator is a tool that can generate skeleton test classes from production code classes and vice versa.  pear install phpunit/PHPUnit_SkeletonGenerator  phpunit-skelgen --test Calculator  Selenium - Is a test tool that allows you to write automated user-interface tests for web applications in any programming language against any HTTP website using any mainstream browser.
  28. 28. Sources  http://phpunit.de/manual/current/en/index.html  https://github.com/sebastianbergmann/phpunit
  29. 29. Thank You
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×