SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
UNIT TESTING
with PHPUnit
about me
        @ferca_tw
             ferran caellas puig

             Core Developer at eyeOS
Computer geek and Open Source enthusiast
What is
UNIT TESTING
class CoreTest extends PHPUnit_framework_TestCase {

    public function TestCount() {
       $testArray = array(‘value1’,’value2’,’value3’);
       $countResult = count($testArray);
       $this->assertEquals(3, $countResult);
    }
}
What you want is to write tests that fail
even though you think they should work,
or tests that succeed even though you
think they should fail.

You want to write tests that will pay you
back with information.
                               Erich Gamma
Writing tests
During development
TDD
TEST-DRIVEN DEVELOPMENT
Writing tests
During debugging
STEPS
1. Verify that you can reproduce the bug.
2. Find the smallest-scale demonstration of the
bug in the code.
3. Write an automated test that fails now but
will succeed when the bug is fixed.
4. Fix the bug.
CODE COVERAGE   The beauty of testing is found not in
                the effort but in the effiency.

                Knowing what should be tested is
                beautiful, and knowing what is being
                tested is beautiful.
                                     Murali Nandigama
public function testEmpty()
           {
             $stack = array();
@depends     $this->assertEmpty($stack);

               return $stack;
           }

           /**
            * @depends testEmpty
            */
           public function testPush(array $stack)
           {
             array_push($stack, 'foo');
             $this->assertEquals('foo', $stack[count($stack)-1]);
             $this->assertNotEmpty($stack);

               return $stack;
           }
/**
                 * @dataProvider provider
                 */
@dataProvider   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)
                   );
                }
@expectedException
                     /**
                      * @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);
                     }
expectOutputString
                     public function testExpectFooActualFoo()
                       {
                         $this->expectOutputString('foo');
                         print 'foo';
                       }
assertArrayHasKey()	
               assertObjectHasA/ribute()	
  
             assertClassHasA/ribute()	
          assertRegExp()	
  
             assertClassHasSta4cA/ribute()	
     assertStringMatchesFormat()	
  
             assertContains()	
                  assertStringMatchesFormatFile()	
  
Assertions
             assertContainsOnly()	
              assertSame()	
  
             assertCount()	
                     assertSelectCount()	
  
             assertEmpty()	
                     assertSelectEquals()	
  
             assertEqualXMLStructure()	
         assertSelectRegExp()	
  
             assertEquals()	
                    assertStringEndsWith()	
  
             assertFalse()	
                     assertStringEqualsFile()	
  
             assertFileEquals()	
                assertStringStartsWith()	
  
             assertFileExists()	
                assertTag()	
  
             assertGreaterThan()	
               assertThat()	
  
             assertGreaterThanOrEqual()	
        assertTrue()	
  
             assertInstanceOf()	
                assertXmlFileEqualsXmlFile()	
  
             assertInternalType()	
              assertXmlStringEqualsXmlFile()	
  
             assertLessThan()	
                  assertXmlStringEqualsXmlString()	
  
             assertLessThanOrEqual()	
  
             assertNull()	
  
setUp()                        setUpBeforeClass()
           tearDown()                     tearDownAfterClass()

            protected function setUp()
Fixtures
             {
               $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));
             }
markTestIncomplete()

Incomplete & Skipped   markTestSkipped()

                       $this->markTestIncomplete(
                            'This test has not been implemented yet.'
                           );



                         phpunit	
  -­‐-­‐verbose	
  SampleTest	
  
                         PHPUnit	
  3.6.0	
  by	
  Sebas4an	
  Bergmann.	
  
                         I	
  
                         Time:	
  0	
  seconds,	
  Memory:	
  3.75Mb	
  
                         	
  
                         There	
  was	
  1	
  incomplete	
  test:	
  
                         	
  
                         1)	
  SampleTest::testSomething	
  
                         This	
  test	
  has	
  not	
  been	
  implemented	
  yet.	
  
                         	
  
                         /home/sb/SampleTest.php:12	
  
                         OK,	
  but	
  incomplete	
  or	
  skipped	
  tests!	
  
                         Tests:	
  1,	
  Asser4ons:	
  1,	
  Incomplete:	
  1.	
  
UNIT TESTING
with PHPUnit

Mais conteúdo relacionado

Mais procurados

Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by Example
Benjamin Eberlei
 

Mais procurados (20)

javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closure
 
Google guava
Google guavaGoogle guava
Google guava
 
Django
Django Django
Django
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by Example
 
Grammatical Optimization
Grammatical OptimizationGrammatical Optimization
Grammatical Optimization
 
Unittesting Bad-Practices by Example
Unittesting Bad-Practices by ExampleUnittesting Bad-Practices by Example
Unittesting Bad-Practices by Example
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Bad test, good test
Bad test, good testBad test, good test
Bad test, good test
 
Next Level Testing
Next Level TestingNext Level Testing
Next Level Testing
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210
 
Message-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applicationsMessage-based communication patterns in distributed Akka applications
Message-based communication patterns in distributed Akka applications
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Unittesting JavaScript with Evidence
Unittesting JavaScript with EvidenceUnittesting JavaScript with Evidence
Unittesting JavaScript with Evidence
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184
 
zinno
zinnozinno
zinno
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
 
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
Unit Testing in Angular(7/8/9) Using Jasmine and Karma Part-2
 

Destaque (10)

Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
My five
My fiveMy five
My five
 
SLA - Alignment and Interaction
SLA - Alignment and InteractionSLA - Alignment and Interaction
SLA - Alignment and Interaction
 
Slide Show
Slide ShowSlide Show
Slide Show
 
SOLID
SOLIDSOLID
SOLID
 
Echoi slide
Echoi slideEchoi slide
Echoi slide
 
Túlavé Garmonty
Túlavé GarmontyTúlavé Garmonty
Túlavé Garmonty
 
My five
My fiveMy five
My five
 
Wal-Mart Harrison NJ
Wal-Mart Harrison NJWal-Mart Harrison NJ
Wal-Mart Harrison NJ
 
Ataque electronico
Ataque electronicoAtaque electronico
Ataque electronico
 

Semelhante a Unit testing with PHPUnit

Test-driven Development for TYPO3
Test-driven Development for TYPO3Test-driven Development for TYPO3
Test-driven Development for TYPO3
Oliver Klee
 
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
smueller_sandsmedia
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
varuntaliyan
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
Js 单元测试框架介绍
Js 单元测试框架介绍Js 单元测试框架介绍
Js 单元测试框架介绍
louieuser
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
whitneyleman54422
 

Semelhante a Unit testing with PHPUnit (20)

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Test-driven Development for TYPO3
Test-driven Development for TYPO3Test-driven Development for TYPO3
Test-driven Development for TYPO3
 
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
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Executable documentation
Executable documentationExecutable documentation
Executable documentation
 
Js 单元测试框架介绍
Js 单元测试框架介绍Js 单元测试框架介绍
Js 单元测试框架介绍
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnit
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.
 
JUnit
JUnitJUnit
JUnit
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Unit testing with PHPUnit

  • 2. about me @ferca_tw ferran caellas puig Core Developer at eyeOS Computer geek and Open Source enthusiast
  • 4. class CoreTest extends PHPUnit_framework_TestCase { public function TestCount() { $testArray = array(‘value1’,’value2’,’value3’); $countResult = count($testArray); $this->assertEquals(3, $countResult); } }
  • 5. What you want is to write tests that fail even though you think they should work, or tests that succeed even though you think they should fail. You want to write tests that will pay you back with information. Erich Gamma
  • 9. STEPS 1. Verify that you can reproduce the bug. 2. Find the smallest-scale demonstration of the bug in the code. 3. Write an automated test that fails now but will succeed when the bug is fixed. 4. Fix the bug.
  • 10. CODE COVERAGE The beauty of testing is found not in the effort but in the effiency. Knowing what should be tested is beautiful, and knowing what is being tested is beautiful. Murali Nandigama
  • 11.
  • 12. public function testEmpty() { $stack = array(); @depends $this->assertEmpty($stack); return $stack; } /** * @depends testEmpty */ public function testPush(array $stack) { array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertNotEmpty($stack); return $stack; }
  • 13. /** * @dataProvider provider */ @dataProvider 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) ); }
  • 14. @expectedException /** * @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); }
  • 15. expectOutputString public function testExpectFooActualFoo() { $this->expectOutputString('foo'); print 'foo'; }
  • 16. assertArrayHasKey()   assertObjectHasA/ribute()   assertClassHasA/ribute()   assertRegExp()   assertClassHasSta4cA/ribute()   assertStringMatchesFormat()   assertContains()   assertStringMatchesFormatFile()   Assertions assertContainsOnly()   assertSame()   assertCount()   assertSelectCount()   assertEmpty()   assertSelectEquals()   assertEqualXMLStructure()   assertSelectRegExp()   assertEquals()   assertStringEndsWith()   assertFalse()   assertStringEqualsFile()   assertFileEquals()   assertStringStartsWith()   assertFileExists()   assertTag()   assertGreaterThan()   assertThat()   assertGreaterThanOrEqual()   assertTrue()   assertInstanceOf()   assertXmlFileEqualsXmlFile()   assertInternalType()   assertXmlStringEqualsXmlFile()   assertLessThan()   assertXmlStringEqualsXmlString()   assertLessThanOrEqual()   assertNull()  
  • 17. setUp() setUpBeforeClass() tearDown() tearDownAfterClass() protected function setUp() Fixtures { $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)); }
  • 18. markTestIncomplete() Incomplete & Skipped markTestSkipped() $this->markTestIncomplete( 'This test has not been implemented yet.' ); phpunit  -­‐-­‐verbose  SampleTest   PHPUnit  3.6.0  by  Sebas4an  Bergmann.   I   Time:  0  seconds,  Memory:  3.75Mb     There  was  1  incomplete  test:     1)  SampleTest::testSomething   This  test  has  not  been  implemented  yet.     /home/sb/SampleTest.php:12   OK,  but  incomplete  or  skipped  tests!   Tests:  1,  Asser4ons:  1,  Incomplete:  1.  
  • 19.

Notas do Editor

  1.  phpunit --coverage-html ./result TwitterTest.php