SlideShare a Scribd company logo
1 of 31
Test in Action – Week 2
  Testing Framework
      Hubert Chan
Testing Framework
• Why using framework?
  – Reinventing the wheel?
  – Frameworks provides
    •   Library / API / Syntactic Sugar
    •   xUnit Pattern
    •   Stub / Mock
    •   Log / Test Coverage
    •   Static Analysis
PHPUnit
• PHPUnit
  – Unit Testing Framework
  – Most common for PHP
  – Open Source
  – Used in known PHP Frameworks
    • Zend Framework
    • Kohana
    • symfony
PHPUnit Installation
• Using pear
  – pear channel discover (only once)
     pear channel-discover pear.phpunit.de
     pear channel-discover components.ez.no
     pear channel-discover pear.symfony-project.com
  – Install PHPUnit
     pear install phpunit/PHPUnit
PHPUnit Example
• Test Code
class StackTest extends PHPUnit_Framework_TestCase {
  public function testPushAndPop() {
    $stack = array();
    $this->assertEquals(0, count($stack));

        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));

        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}
PHPUnit Test Cases Rule
• General Rule
  1. The tests for a class Class go into a class ClassTest.
  2. ClassTest inherits (most of the time) from
     PHPUnit_Framework_TestCase.
  3. The tests are public methods that are named test*.
  4. Write Assertions
Data Provider
• Data Provider
  – Return an iterative object (Iterator interface)
  – Use for data-driven testing
     • Like ACM Input data
  – Use it carefully
Data Provider Sample
• Test Code
class DataTest extends PHPUnit_Framework_TestCase {
  /**
  * @dataProvider provider
  */
  public function testAdd($a, $b, $c) {
     $this->assertEquals($c, $a + $b);
  }
    public function   provider() {
      return array(
        array(0, 0,   0),
        array(0, 1,   1),
        array(1, 0,   1),
        array(1, 1,   3)
      );
    }
}
Testing Exception
• Testing Exception
  – Testing for failure cases
  – Error Handling
  – Examine
     • Exception Type
     • Exception Message
     • Exception Code
Testing Exception Sample
• Test Code
class ExceptionTest extends PHPUnit_Framework_TestCase {
  /**
  * @expectedException        InvalidArgumentException
  * @expectedExceptionMessage Right Message
  */
  public function testExceptionHasRightMessage() {
    throw new InvalidArgumentException('Some Message', 10);
  }
    /**
    * @expectedException     InvalidArgumentException
    * @expectedExceptionCode 20
    */
    public function testExceptionHasRightCode() {
      throw new InvalidArgumentException('Some Message', 10);
    }
}
Testing Exception Sample
• Test Code
class ExceptionTest extends PHPUnit_Framework_TestCase {

    public function testExceptionHasRightMessage() {
      $this->setExpectedException(
        'InvalidArgumentException', 'Right Message'
      );
      throw new InvalidArgumentException('Some Message', 10);
    }
    public function testExceptionHasRightCode() {
      $this->setExpectedException(
        'InvalidArgumentException', 'Right Message', 20
      );
      throw new InvalidArgumentException(
        'The Right Message', 10
      );
    }
}
Assertion
• Assertions
  – assertEquals
  – assertTrue / assertFalse
  – assertContains
  – and etc.
Assertion Guideline
• Assertion Guideline
  – Using best suitable assertion
  – Some assertions are more easy to use
     • assertXmlFileEqualsXmlFile()
     • assertRegExp()
     • and etc.
  – Make assertion contains useful message
Assertion Compare - Equals
• Test Code
class EqualTest extends PHPUnit_Framework_TestCase {

    public function test_AssertTrue() {
        $this->assertTrue("123" === "456");
    }

    public function test_AssertEquals() {
        $this->assertEquals("123", "456");
    }
}
Assertion Compare – Equals (cont.)
• Output
1) EqualTest::test_AssertTrue
Failed asserting that <boolean:false> is true.

/usr/home/hubert/tmp/php/equal_compare.php:6

2) EqualTest::test_AssertEquals
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-123
+456

/usr/home/hubert/tmp/php/equal_compare.php:10
Assertion Message
• Prototype
 assertEmpty(mixed $actual[, string $message = ''])

• Test Code
 class EqualTest extends PHPUnit_Framework_TestCase {
   public function test_AssertMessage() {
     $handler = new LogViewHandler();
     $this->assertNotEmpty(
       $handler->generate_ajax(),
       "generate_ajax() should not be empty!!"
     );
   }
 }
Assertion Message - Output
• Output
1) EqualTest::test_AssertMessage
generate_ajax() should not be empty!!
Failed asserting that a string is not empty.

/usr/home/hubert/tmp/php/equal_compare.php:24
xUnit Architecture
• Test Case
• Test fixtures
  – Pre-action / Post-action needed to run a test
• Test Suites
  – A set of tests that all share the same fixture
  – The order of the tests shouldn't matter
Test Fixtures
• Fixtures
  – Avoid duplicate Arrangement code
  – Make test cases focus on Action and Assertion
• Test Fixtures
  – setUp()
     • Pre-action before each test case
  – tearDown()
     • Post-action after each test case
Test Execution
Fixture Example
• Test Code
class StackTest extends PHPUnit_Framework_TestCase {
  protected $stack;
    protected function setUp() {
      $this->stack = array();
    }
    public function testEmpty() {
      $this->assertTrue(empty($this->stack));
    }
    public function testPush() {
      array_push($this->stack, 'foo');
      $this->assertEquals('foo', $this->stack[count($this->stack)-1]);
      $this->assertFalse(empty($this->stack));
    }
    public function testPop() {
      array_push($this->stack, 'foo');
      $this->assertEquals('foo', array_pop($this->stack));
      $this->assertTrue(empty($this->stack));
    }
}
Fixture Guideline
• Fixture Guideline
  – Only use setUp and tearDown to initialize or
    destroy objects that are shared throughout the
    test class in all the tests
     • Otherwise, readers don’t know which tests use the
       logic inside the setup method and which don’t
Sharing Fixture
• Sharing Fixture
  – Really few reason to share fixtures
  – Good example
       • Reuse database connection
  – Sample Test Code
  class DatabaseTest extends PHPUnit_Framework_TestCase {
    protected static $dbh;

      public static function setUpBeforeClass() {
        self::$dbh = new PDO('sqlite::memory:');
      }

      public static function tearDownAfterClass() {
        self::$dbh = NULL;
      }
  }
Organize PHPUnit Tests
• Mapping for production code and test
 middleware_rev                  tests
 |── handlers                    |── _log
 │ └── _details                  |── bootstrap.php
 │   |── TRConverter.class.php   |── handlers
 │   └── tmql                    │ └── _details
 │      └──                      │     |── TRConverterTest.php
 TMQLEscape.class.php            │     └── tmql
 └── lib                         │       └──
                                 TMQLEscapeTest.php
                                 |── lib
                                 └── phpunit.xml
Execute PHPUnit tests
• Execute all tests
  % phpunit
• Execute all tests in a subdirectory
  % phpunit handlers
• Execute single test in a subdirectory
  % phpunit --filter TMQLEscapeTest handlers
Test Naming
• Test Class Name
  – For class name “Util”
  – Test class name should be “UtilTest”
  – Test filename should be “UtilTest.php”
Test Naming
• Function Name
  – Test function name should be
    test_<function>_<scenario>_<expect_behavior>
  – Example
    • test_escape_evenBackSlashesData_successEscape
Single Assertion / Concept per Test
• Single Assertion / Concept per Test
  – If a test failed, the cause may be more obvious
  – Compare
     • PHPUnit Example
     • Fixture Example
  – testPushPop test 3 concepts
     • Test for Empty / Push / Pop
Clean Test
• Clean Test
  – Keeping Tests Clean
  – Or you will not maintain them
  – Test codes are as important code as production
  – Write Test API / Utility / DSL
  – Clean TDD cheat sheet
     • http://www.planetgeek.ch/2011/01/04/clean-code-
       and-clean-tdd-cheat-sheets/
F.I.R.S.T
• F.I.R.S.T
   – Fast
   – Independent (isolated)
   – Repeatable
   – Self-Validating
   – Timely
References
• Clean Code
• The Art of Unit Testing

More Related Content

What's hot

Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitMichelangelo van Dam
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
 
Py.test
Py.testPy.test
Py.testsoasme
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitMichelangelo van Dam
 
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 2013Michelangelo van Dam
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnitvaruntaliyan
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objectsLim Chanmann
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best PracticesEdorian
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in LaravelAhmed Yahia
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to heroJeremy Cook
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 

What's hot (20)

Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
Py.test
Py.testPy.test
Py.test
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
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
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best Practices
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in Laravel
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 

Viewers also liked

ABCs Conservation Programs
ABCs Conservation ProgramsABCs Conservation Programs
ABCs Conservation ProgramsDuaneHovorka
 
Wikimedia Indonesia Laporan Tahunan 2012
Wikimedia Indonesia Laporan Tahunan 2012Wikimedia Indonesia Laporan Tahunan 2012
Wikimedia Indonesia Laporan Tahunan 2012Wikimedia Indonesia
 
利用Init connect做mysql clients stat 用户审计
 利用Init connect做mysql clients stat 用户审计 利用Init connect做mysql clients stat 用户审计
利用Init connect做mysql clients stat 用户审计Dehua Yang
 
Elena vocabulary 2013
Elena vocabulary 2013Elena vocabulary 2013
Elena vocabulary 2013PEDH
 
What Does Islam Mean
What Does Islam MeanWhat Does Islam Mean
What Does Islam MeanSyukran
 
How our Muhammad (pbuh) become a prophet
How our Muhammad (pbuh) become a prophetHow our Muhammad (pbuh) become a prophet
How our Muhammad (pbuh) become a prophetSyukran
 
Mobile technologies briefing
Mobile technologies briefingMobile technologies briefing
Mobile technologies briefingkabbott
 
Tata Cara Syarat Dan Surat Referensi
Tata Cara Syarat Dan Surat ReferensiTata Cara Syarat Dan Surat Referensi
Tata Cara Syarat Dan Surat ReferensiWikimedia Indonesia
 
Syukran brand positioning & Strategy 2010
Syukran brand positioning & Strategy 2010Syukran brand positioning & Strategy 2010
Syukran brand positioning & Strategy 2010Syukran
 
Theme 2 iditarod moondance kid vocabulary flash cards feb2013
Theme 2   iditarod moondance kid vocabulary flash cards feb2013Theme 2   iditarod moondance kid vocabulary flash cards feb2013
Theme 2 iditarod moondance kid vocabulary flash cards feb2013PEDH
 
David Rodnitzky
David RodnitzkyDavid Rodnitzky
David Rodnitzkytieadmin
 
Stockholm Presentation To Wsp Council On Results Of Iys 19 August09
Stockholm Presentation To Wsp Council On Results Of Iys 19 August09Stockholm Presentation To Wsp Council On Results Of Iys 19 August09
Stockholm Presentation To Wsp Council On Results Of Iys 19 August09Yehude Simon Valcárcel
 
Remix: putting kids in the picture
Remix: putting kids in the pictureRemix: putting kids in the picture
Remix: putting kids in the pictureClaudia Leigh
 
Impurities and their rulings
Impurities and their rulingsImpurities and their rulings
Impurities and their rulingsSyukran
 
Wiki Women Camp 2012 IIEF Report
Wiki Women Camp 2012 IIEF ReportWiki Women Camp 2012 IIEF Report
Wiki Women Camp 2012 IIEF ReportWikimedia Indonesia
 
03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...
03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...
03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...West Ridge Marriage Ministry
 
Proposal Bebaskan Pengetahuan 2012
Proposal Bebaskan Pengetahuan 2012Proposal Bebaskan Pengetahuan 2012
Proposal Bebaskan Pengetahuan 2012Wikimedia Indonesia
 

Viewers also liked (20)

ABCs Conservation Programs
ABCs Conservation ProgramsABCs Conservation Programs
ABCs Conservation Programs
 
DoInk2
DoInk2DoInk2
DoInk2
 
Wikimedia Indonesia Laporan Tahunan 2012
Wikimedia Indonesia Laporan Tahunan 2012Wikimedia Indonesia Laporan Tahunan 2012
Wikimedia Indonesia Laporan Tahunan 2012
 
利用Init connect做mysql clients stat 用户审计
 利用Init connect做mysql clients stat 用户审计 利用Init connect做mysql clients stat 用户审计
利用Init connect做mysql clients stat 用户审计
 
Kelas menulis Wikipedia I
Kelas menulis Wikipedia IKelas menulis Wikipedia I
Kelas menulis Wikipedia I
 
Elena vocabulary 2013
Elena vocabulary 2013Elena vocabulary 2013
Elena vocabulary 2013
 
What Does Islam Mean
What Does Islam MeanWhat Does Islam Mean
What Does Islam Mean
 
How our Muhammad (pbuh) become a prophet
How our Muhammad (pbuh) become a prophetHow our Muhammad (pbuh) become a prophet
How our Muhammad (pbuh) become a prophet
 
Mobile technologies briefing
Mobile technologies briefingMobile technologies briefing
Mobile technologies briefing
 
Tata Cara Syarat Dan Surat Referensi
Tata Cara Syarat Dan Surat ReferensiTata Cara Syarat Dan Surat Referensi
Tata Cara Syarat Dan Surat Referensi
 
Syukran brand positioning & Strategy 2010
Syukran brand positioning & Strategy 2010Syukran brand positioning & Strategy 2010
Syukran brand positioning & Strategy 2010
 
Theme 2 iditarod moondance kid vocabulary flash cards feb2013
Theme 2   iditarod moondance kid vocabulary flash cards feb2013Theme 2   iditarod moondance kid vocabulary flash cards feb2013
Theme 2 iditarod moondance kid vocabulary flash cards feb2013
 
David Rodnitzky
David RodnitzkyDavid Rodnitzky
David Rodnitzky
 
Stockholm Presentation To Wsp Council On Results Of Iys 19 August09
Stockholm Presentation To Wsp Council On Results Of Iys 19 August09Stockholm Presentation To Wsp Council On Results Of Iys 19 August09
Stockholm Presentation To Wsp Council On Results Of Iys 19 August09
 
Remix: putting kids in the picture
Remix: putting kids in the pictureRemix: putting kids in the picture
Remix: putting kids in the picture
 
Impurities and their rulings
Impurities and their rulingsImpurities and their rulings
Impurities and their rulings
 
Papat limpad
Papat limpadPapat limpad
Papat limpad
 
Wiki Women Camp 2012 IIEF Report
Wiki Women Camp 2012 IIEF ReportWiki Women Camp 2012 IIEF Report
Wiki Women Camp 2012 IIEF Report
 
03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...
03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...
03 15 09 Opening The Door To Effective Communication Part I Keys To Effective...
 
Proposal Bebaskan Pengetahuan 2012
Proposal Bebaskan Pengetahuan 2012Proposal Bebaskan Pengetahuan 2012
Proposal Bebaskan Pengetahuan 2012
 

Similar to Test in action week 2

Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09Michelangelo van Dam
 
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] 2023Mark Niebergall
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitJames Fuller
 
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 2022Mark Niebergall
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentMark Niebergall
 
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
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)ENDelt260
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnitShouvik Chatterjee
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best PracticesJitendra Zaa
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 

Similar to Test in action week 2 (20)

Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
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
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
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
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
3 j unit
3 j unit3 j unit
3 j unit
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
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
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnit
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
Phpunit
PhpunitPhpunit
Phpunit
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit testing
Unit testingUnit testing
Unit testing
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

Test in action week 2

  • 1. Test in Action – Week 2 Testing Framework Hubert Chan
  • 2. Testing Framework • Why using framework? – Reinventing the wheel? – Frameworks provides • Library / API / Syntactic Sugar • xUnit Pattern • Stub / Mock • Log / Test Coverage • Static Analysis
  • 3. PHPUnit • PHPUnit – Unit Testing Framework – Most common for PHP – Open Source – Used in known PHP Frameworks • Zend Framework • Kohana • symfony
  • 4. PHPUnit Installation • Using pear – pear channel discover (only once) pear channel-discover pear.phpunit.de pear channel-discover components.ez.no pear channel-discover pear.symfony-project.com – Install PHPUnit pear install phpunit/PHPUnit
  • 5. PHPUnit Example • Test Code class StackTest extends PHPUnit_Framework_TestCase { public function testPushAndPop() { $stack = array(); $this->assertEquals(0, count($stack)); array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertEquals(1, count($stack)); $this->assertEquals('foo', array_pop($stack)); $this->assertEquals(0, count($stack)); } }
  • 6. PHPUnit Test Cases Rule • General Rule 1. The tests for a class Class go into a class ClassTest. 2. ClassTest inherits (most of the time) from PHPUnit_Framework_TestCase. 3. The tests are public methods that are named test*. 4. Write Assertions
  • 7. Data Provider • Data Provider – Return an iterative object (Iterator interface) – Use for data-driven testing • Like ACM Input data – Use it carefully
  • 8. Data Provider Sample • Test Code class DataTest extends PHPUnit_Framework_TestCase { /** * @dataProvider provider */ public function testAdd($a, $b, $c) { $this->assertEquals($c, $a + $b); } public function provider() { return array( array(0, 0, 0), array(0, 1, 1), array(1, 0, 1), array(1, 1, 3) ); } }
  • 9. Testing Exception • Testing Exception – Testing for failure cases – Error Handling – Examine • Exception Type • Exception Message • Exception Code
  • 10. Testing Exception Sample • Test Code class ExceptionTest extends PHPUnit_Framework_TestCase { /** * @expectedException InvalidArgumentException * @expectedExceptionMessage Right Message */ public function testExceptionHasRightMessage() { throw new InvalidArgumentException('Some Message', 10); } /** * @expectedException InvalidArgumentException * @expectedExceptionCode 20 */ public function testExceptionHasRightCode() { throw new InvalidArgumentException('Some Message', 10); } }
  • 11. Testing Exception Sample • Test Code class ExceptionTest extends PHPUnit_Framework_TestCase { public function testExceptionHasRightMessage() { $this->setExpectedException( 'InvalidArgumentException', 'Right Message' ); throw new InvalidArgumentException('Some Message', 10); } public function testExceptionHasRightCode() { $this->setExpectedException( 'InvalidArgumentException', 'Right Message', 20 ); throw new InvalidArgumentException( 'The Right Message', 10 ); } }
  • 12. Assertion • Assertions – assertEquals – assertTrue / assertFalse – assertContains – and etc.
  • 13. Assertion Guideline • Assertion Guideline – Using best suitable assertion – Some assertions are more easy to use • assertXmlFileEqualsXmlFile() • assertRegExp() • and etc. – Make assertion contains useful message
  • 14. Assertion Compare - Equals • Test Code class EqualTest extends PHPUnit_Framework_TestCase { public function test_AssertTrue() { $this->assertTrue("123" === "456"); } public function test_AssertEquals() { $this->assertEquals("123", "456"); } }
  • 15. Assertion Compare – Equals (cont.) • Output 1) EqualTest::test_AssertTrue Failed asserting that <boolean:false> is true. /usr/home/hubert/tmp/php/equal_compare.php:6 2) EqualTest::test_AssertEquals Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -123 +456 /usr/home/hubert/tmp/php/equal_compare.php:10
  • 16. Assertion Message • Prototype assertEmpty(mixed $actual[, string $message = '']) • Test Code class EqualTest extends PHPUnit_Framework_TestCase { public function test_AssertMessage() { $handler = new LogViewHandler(); $this->assertNotEmpty( $handler->generate_ajax(), "generate_ajax() should not be empty!!" ); } }
  • 17. Assertion Message - Output • Output 1) EqualTest::test_AssertMessage generate_ajax() should not be empty!! Failed asserting that a string is not empty. /usr/home/hubert/tmp/php/equal_compare.php:24
  • 18. xUnit Architecture • Test Case • Test fixtures – Pre-action / Post-action needed to run a test • Test Suites – A set of tests that all share the same fixture – The order of the tests shouldn't matter
  • 19. Test Fixtures • Fixtures – Avoid duplicate Arrangement code – Make test cases focus on Action and Assertion • Test Fixtures – setUp() • Pre-action before each test case – tearDown() • Post-action after each test case
  • 21. Fixture Example • Test Code class StackTest extends PHPUnit_Framework_TestCase { protected $stack; protected function setUp() { $this->stack = array(); } public function testEmpty() { $this->assertTrue(empty($this->stack)); } public function testPush() { array_push($this->stack, 'foo'); $this->assertEquals('foo', $this->stack[count($this->stack)-1]); $this->assertFalse(empty($this->stack)); } public function testPop() { array_push($this->stack, 'foo'); $this->assertEquals('foo', array_pop($this->stack)); $this->assertTrue(empty($this->stack)); } }
  • 22. Fixture Guideline • Fixture Guideline – Only use setUp and tearDown to initialize or destroy objects that are shared throughout the test class in all the tests • Otherwise, readers don’t know which tests use the logic inside the setup method and which don’t
  • 23. Sharing Fixture • Sharing Fixture – Really few reason to share fixtures – Good example • Reuse database connection – Sample Test Code class DatabaseTest extends PHPUnit_Framework_TestCase { protected static $dbh; public static function setUpBeforeClass() { self::$dbh = new PDO('sqlite::memory:'); } public static function tearDownAfterClass() { self::$dbh = NULL; } }
  • 24. Organize PHPUnit Tests • Mapping for production code and test middleware_rev tests |── handlers |── _log │ └── _details |── bootstrap.php │ |── TRConverter.class.php |── handlers │ └── tmql │ └── _details │ └── │ |── TRConverterTest.php TMQLEscape.class.php │ └── tmql └── lib │ └── TMQLEscapeTest.php |── lib └── phpunit.xml
  • 25. Execute PHPUnit tests • Execute all tests % phpunit • Execute all tests in a subdirectory % phpunit handlers • Execute single test in a subdirectory % phpunit --filter TMQLEscapeTest handlers
  • 26. Test Naming • Test Class Name – For class name “Util” – Test class name should be “UtilTest” – Test filename should be “UtilTest.php”
  • 27. Test Naming • Function Name – Test function name should be test_<function>_<scenario>_<expect_behavior> – Example • test_escape_evenBackSlashesData_successEscape
  • 28. Single Assertion / Concept per Test • Single Assertion / Concept per Test – If a test failed, the cause may be more obvious – Compare • PHPUnit Example • Fixture Example – testPushPop test 3 concepts • Test for Empty / Push / Pop
  • 29. Clean Test • Clean Test – Keeping Tests Clean – Or you will not maintain them – Test codes are as important code as production – Write Test API / Utility / DSL – Clean TDD cheat sheet • http://www.planetgeek.ch/2011/01/04/clean-code- and-clean-tdd-cheat-sheets/
  • 30. F.I.R.S.T • F.I.R.S.T – Fast – Independent (isolated) – Repeatable – Self-Validating – Timely
  • 31. References • Clean Code • The Art of Unit Testing