SlideShare ist ein Scribd-Unternehmen logo
1 von 36
From Zero to Hero
WHAT IS UNIT TESTING…
         
     and why is it a Good Thing™?
WHAT IS UNIT TESTING?
          
 “In computer programming, unit testing is a method by
  which individual units of source code are tested to
  determine if they are fit for use. A unit is the smallest
  testable part of an application.” Wikipedia
HAVE ANY OF THESE
   EVER APPLIED TO YOU?
                         
 You have a piece of code that everyone is too
  terrified to touch.
 You’re too scared to refactor or change a piece of
  code because you can’t predict the impact it will
  have on your application.
 Releases are a complete nightmare.
 You’ve had to work late or through a weekend to
  track down a bug.
WRITING TESTS IS HARD, WRITING
GOOD TESTS IS EVEN HARDER…
…BUT WORTHWHILE
           
 A study conducted by Microsoft and IBM showed
  writing tests can add 15%-35% to development time
  but reduce the number of bugs by 40%-90%!
 Writing code that is easily testable encourages best
  practices, such as SOLID principles.
 Having a set of unit tests can help you make sure
  your deployments are painless rather than painful
 None of us want to be stuck at work all weekend
  trying to work out why a code change has broken
  the whole application.
WHAT IS PHPUNIT?
        
INTRODUCTION TO
           PHPUNIT
             
 PHPUnit is a unit testing framework written in
  PHP, created by Sebastian Bergman.
 Part of the xUnit family of testing frameworks.
 While there are other unit testing frameworks for
  PHP (such as SimpleTest or Atoum) PHPUnit has
  become the de facto standard.
 Major frameworks, such as Zend, Symfony and
  Cake, and many other PHP projects such as Doctrine
  have test suites written with PHPUnit.
INSTALLING PHPUNIT
         
REQUIREMENTS
                
 Minimum requirement is PHP 5.2.7 but 5.3.X is
  recommended.
 If you want code coverage analysis (you do!) you
  need to install the PECL xDebug extension.
 Best installed via the PEAR installer so you need to
  have run the pear installation.
INSTALLING VIA PEAR
            
 If installing via PEAR you need two commands to
  get up and running:




 Full installation instructions (including other
  optional PHPUnit modules) can be found at
  http://www.phpunit.de/manual/3.6/en/installatio
  n.html
WRITING TESTS
     
TEST WRITING BEST
          PRACTICES
             
 The general aim is to make sure every possible path
  through your code is exercised at least once in a test.
 This means you need to write tests that exercise error
  conditions too.
 Rule of thumb: one test method per expected
  outcome per method tested.
 Have descriptive test method names.
 Name the test class after the class being tested.
TEST BASICS
                       
 Simply add ‘require_once PHPUnit/Autoload.php’ to each test
  file.
 A PHPUnit test is a class that (usually) extends
  PHPUnit_Framework_TestCase.
 The class name should end with the word ‘Test’, e.g. ‘FooBarTest’.
 Each test class should be in its own file named after the class, e.g.
  ‘FooBarTest.php’.
 Each test method name must begin with the word ‘test’, e.g.
  ‘testSomethingWorks’ or have an @test annotation.
 Test methods must be public.
 The class must contain one or more methods that perform tests or
  the test case will fail.
 A test method must contain one or more assertions, be marked as
  incomplete or skipped.
TEST FIXTURES
                    
 A fixture in a test is something (usually an object) that you want
  to test.
 Also known as System Under Test (SUT).
 PHPUnit will set up fixtures for you if you add protected
  methods setUp and optionally tearDown in your test class.
 You provide code to create/destroy fixtures in these methods.
 These methods are called before and after each test method so
  that each test runs on fresh fixtures.
 setUpBeforeClass and tearDownAfterClass are also available.
  These are run once at the beginning and end of the test class.
WRITING ASSERTIONS
            
 Assertions are used to test expected behaviour from
  your SUT.
 PHPUnit provides many different assertions for all
  sorts of needs, e.g.
  assertEquals, assertEmpty, assertTrue, assertType, et
  c.
 You can also test output using expectOutputString.
 More complicated assertions can be constructed
  using assertThat.
 For a test to pass all assertions must evaluate to true.
ANNOTATIONS
               
 PHPUnit supports annotations to give instructions to
  the test method being executed.
 Annotations are included in block comments before
  the method and always begin with an ‘@’.
 Examples:
  @depends, @expectedException, @dataProvider.
 Full details on supported annotations at
  http://www.phpunit.de/manual/3.6/en/appendix
  es.annotations.html
DATA PROVIDERS
              
 A data provider is a method that returns an array of
  values to use in a test.
 PHPUnit will call the related test method once for
  each set of data, passing the values as arguments to
  the method.
 Set using the @dataProvider annotation.
 Allows you to easily add extra values to test with.
 Also makes tests shorter and more concise by
  keeping values to test with out of test methods.
TESTING EXCEPTIONS
             
 You can tell PHPUnit that a test should expect an
  exception.
 This can be done in two ways:
   Through the method
    setExpectedException($exception, $message = ‘’, $code
    = null)
   Through
    @expectedException, @expectedExceptionMessage, @e
    xpectedExceptionCode annotations.
 PHP errors such as warnings are converted into
  exceptions by PHPUnit. These can also be tested for.
MOCK OBJECTS
        
One of the most powerful features of PHPUnit.
WTF IS A MOCK OBJECT?
          
 Allows you to replace a dependency of your SUT with an
  object that has predefined behaviour.
 The mock object becomes part of the test. If the methods
  defined are not called as expected the test fails.
 Proper use of mock objects allow you to make sure you’re
  only testing the SUT and not other code.
 Helps to ensure that if a test fails it’s in the SUT, not a
  dependency.
 However, you need to be using Dependency Injection to
  use mock objects.
MOCK OBJECT BASICS
           
 PHPUnit creates a mock by sub-classing the original
  object.
 Once you have a mock object you can define what
  methods you expect to be called on it, with what
  arguments and what the mock should do.
OTHER MOCK OBJECT
          USES
           
 Mock objects allow you to test concrete methods of
  abstract classes with getMockForAbstractClass.
 You can create a mock object representing a SOAP
  web service using getMockFromWsdl.
 PHPUnit has experimental support for mocking out
  file system calls using the package vfsStream.
 More information at
  http://www.phpunit.de/manual/3.6/en/test-
  doubles.html.
RUNNING TESTS
     
COMMAND LINE RUNNER
        
 Tests are normally run from the command line with the
  phpunit command.
 Just typing phpunit will get a ‘help’ output.
 Passing the name of the test will run just that test.
 You can also pass a path to a directory to run all tests in it
  or the name of a test file to run tests in that file.
 PHPUnit prints a ‘.’ for each test passed, ‘F’ for a
  failure, ‘E’ for an error, ‘I’ for incomplete or ‘S’ for
  skipped.
 More information is also printed for anything other than a
  pass.
SAMPLE COMMAND LINE
       OUTPUT
         
OTHER WAYS TO RUN
          TESTS
           
 Many IDE’s such as Zend Studio include PHPUnit
  integration. This enables you to write and run tests
  from within the IDE.
 Running tests can be integrated into continuous
  integration servers such as Jenkins.
 In this case your full test suite can be run
  automatically with each edit to your code.
 Any test failure will mean the build fails.
CODE COVERAGE
           ANALYSIS…
               
or how to make sure you’re not feeling a false sense of security.
WTF IS CODE
             COVERAGE?
                 
 Code coverage tells you how much of your code is
  covered by tests.
 PHPUnit can generate code coverage reports in a number
  of formats including HTML but…
 You must have installed xDebug. (pecl install xdebug)
 Helps to avoid a false sense of security.
 Code coverage threshold percentage can be added to
  continuous integration builds.
 Add code coverage by passing the –coverage-xxx
  option, eg. phpunit –coverage-html ./reports ./
PHPUNIT TEST
 EXTENSIONS
     
Writing tests for different situations.
INTRO TO EXTENSIONS
            
 PHPUnit supports a number of extensions that allow
  you to write specialised tests.
 These include working with
  databases, Selenium, and running profiling with
  XHProf.
 Full details at
  http://www.phpunit.de/manual/3.6/en/installatio
  n.html.
TESTING WITH
               DATABASES
                   
 To do this install the DbUnit    You need to provide a
  extension, eg. ‘pear install      schema with tables for
  phpunit/DbUnit’                   PHPUnit to use.
 However, where possible          getConnection must return a
                                    PDO instance for PHPUnit
  avoid tests using a database      to use.
  by using mock objects.
                                   getDataSet returns data to
 Test case must extend             populate database tables
  ‘PHPUnit_Extensions_Datab         with.
  ase_TestCase’.                   PHPUnit truncates tables
 Defines two extra methods         before each test run and
  that you must implement:          inserts data. This means
  getConnection and                 each test runs with a fresh
                                    set of predictable data.
  getDataSet.
PHPUNIT CONFIG
     
ADDING A CONFIG FILE
          
 Options can be passed to PHPUnit through the command
  line but it also supports adding an XML config file.
 This can include a number of options such as where to
  find test cases and which directories to include for code
  coverage analysis.
 To use this just create the file and name it
  phpunit.xml, adding it to the root of your tests directory.
 Especially useful when running tests as part of a CI build.
 Full details at
  http://www.phpunit.de/manual/3.6/en/appendixes.co
  nfiguration.html
LET’S WRITE SOME TESTS!
          
QUESTIONS?
    

Weitere ähnliche Inhalte

Was ist angesagt?

JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
Tu primer script en Katalon - Paso a Paso
Tu primer script en Katalon - Paso a PasoTu primer script en Katalon - Paso a Paso
Tu primer script en Katalon - Paso a PasoArgentesting
 
Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation FrameworkSetting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Frameworkvaluebound
 
Php server variables
Php server variablesPhp server variables
Php server variablesJIGAR MAKHIJA
 
Testing with laravel
Testing with laravelTesting with laravel
Testing with laravelDerek Binkley
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses étatsJosé Paumard
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with seleniumTzirla Rozental
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Frameworklaurent bristiel
 
테스트자동화와 TDD
테스트자동화와 TDD테스트자동화와 TDD
테스트자동화와 TDDSunghyouk Bae
 

Was ist angesagt? (20)

Junit
JunitJunit
Junit
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Introduction to robot framework
Introduction to robot frameworkIntroduction to robot framework
Introduction to robot framework
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Tu primer script en Katalon - Paso a Paso
Tu primer script en Katalon - Paso a PasoTu primer script en Katalon - Paso a Paso
Tu primer script en Katalon - Paso a Paso
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation FrameworkSetting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Framework
 
Php server variables
Php server variablesPhp server variables
Php server variables
 
Testing with laravel
Testing with laravelTesting with laravel
Testing with laravel
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Framework
 
테스트자동화와 TDD
테스트자동화와 TDD테스트자동화와 TDD
테스트자동화와 TDD
 

Ähnlich wie PHPUnit: from zero to hero

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_v2Tricode (part of Dept)
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPressHarshad Mane
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitJames Fuller
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHPRadu Murzea
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)Amr E. Mohamed
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yiimadhavi Ghadge
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
Getting started with PHPUnit
Getting started with PHPUnitGetting started with PHPUnit
Getting started with PHPUnitKhyati Gala
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 

Ähnlich wie PHPUnit: from zero to hero (20)

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
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPress
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHP
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Zend Framework 2 - PHPUnit
Zend Framework 2 - PHPUnitZend Framework 2 - PHPUnit
Zend Framework 2 - PHPUnit
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Rc2010 tdd
Rc2010 tddRc2010 tdd
Rc2010 tdd
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Php unit
Php unitPhp unit
Php unit
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yii
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Python and test
Python and testPython and test
Python and test
 
Getting started with PHPUnit
Getting started with PHPUnitGetting started with PHPUnit
Getting started with PHPUnit
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 

Mehr von Jeremy Cook

Unit test your java architecture with ArchUnit
Unit test your java architecture with ArchUnitUnit test your java architecture with ArchUnit
Unit test your java architecture with ArchUnitJeremy Cook
 
Tracking your data across the fourth dimension
Tracking your data across the fourth dimensionTracking your data across the fourth dimension
Tracking your data across the fourth dimensionJeremy Cook
 
Tracking your data across the fourth dimension
Tracking your data across the fourth dimensionTracking your data across the fourth dimension
Tracking your data across the fourth dimensionJeremy Cook
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to DomainJeremy Cook
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to DomainJeremy Cook
 
Track your data across the fourth dimension
Track your data across the fourth dimensionTrack your data across the fourth dimension
Track your data across the fourth dimensionJeremy Cook
 
Accelerate your web app with a layer of Varnish
Accelerate your web app with a layer of VarnishAccelerate your web app with a layer of Varnish
Accelerate your web app with a layer of VarnishJeremy Cook
 
Turbo charge your logs
Turbo charge your logsTurbo charge your logs
Turbo charge your logsJeremy Cook
 
Turbo charge your logs
Turbo charge your logsTurbo charge your logs
Turbo charge your logsJeremy Cook
 

Mehr von Jeremy Cook (9)

Unit test your java architecture with ArchUnit
Unit test your java architecture with ArchUnitUnit test your java architecture with ArchUnit
Unit test your java architecture with ArchUnit
 
Tracking your data across the fourth dimension
Tracking your data across the fourth dimensionTracking your data across the fourth dimension
Tracking your data across the fourth dimension
 
Tracking your data across the fourth dimension
Tracking your data across the fourth dimensionTracking your data across the fourth dimension
Tracking your data across the fourth dimension
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 
Track your data across the fourth dimension
Track your data across the fourth dimensionTrack your data across the fourth dimension
Track your data across the fourth dimension
 
Accelerate your web app with a layer of Varnish
Accelerate your web app with a layer of VarnishAccelerate your web app with a layer of Varnish
Accelerate your web app with a layer of Varnish
 
Turbo charge your logs
Turbo charge your logsTurbo charge your logs
Turbo charge your logs
 
Turbo charge your logs
Turbo charge your logsTurbo charge your logs
Turbo charge your logs
 

Kürzlich hochgeladen

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
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...DianaGray10
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Kürzlich hochgeladen (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

PHPUnit: from zero to hero

  • 2. WHAT IS UNIT TESTING…  and why is it a Good Thing™?
  • 3. WHAT IS UNIT TESTING?   “In computer programming, unit testing is a method by which individual units of source code are tested to determine if they are fit for use. A unit is the smallest testable part of an application.” Wikipedia
  • 4. HAVE ANY OF THESE EVER APPLIED TO YOU?   You have a piece of code that everyone is too terrified to touch.  You’re too scared to refactor or change a piece of code because you can’t predict the impact it will have on your application.  Releases are a complete nightmare.  You’ve had to work late or through a weekend to track down a bug.
  • 5. WRITING TESTS IS HARD, WRITING GOOD TESTS IS EVEN HARDER…
  • 6. …BUT WORTHWHILE   A study conducted by Microsoft and IBM showed writing tests can add 15%-35% to development time but reduce the number of bugs by 40%-90%!  Writing code that is easily testable encourages best practices, such as SOLID principles.  Having a set of unit tests can help you make sure your deployments are painless rather than painful  None of us want to be stuck at work all weekend trying to work out why a code change has broken the whole application.
  • 8. INTRODUCTION TO PHPUNIT   PHPUnit is a unit testing framework written in PHP, created by Sebastian Bergman.  Part of the xUnit family of testing frameworks.  While there are other unit testing frameworks for PHP (such as SimpleTest or Atoum) PHPUnit has become the de facto standard.  Major frameworks, such as Zend, Symfony and Cake, and many other PHP projects such as Doctrine have test suites written with PHPUnit.
  • 10. REQUIREMENTS   Minimum requirement is PHP 5.2.7 but 5.3.X is recommended.  If you want code coverage analysis (you do!) you need to install the PECL xDebug extension.  Best installed via the PEAR installer so you need to have run the pear installation.
  • 11. INSTALLING VIA PEAR   If installing via PEAR you need two commands to get up and running:  Full installation instructions (including other optional PHPUnit modules) can be found at http://www.phpunit.de/manual/3.6/en/installatio n.html
  • 13. TEST WRITING BEST PRACTICES   The general aim is to make sure every possible path through your code is exercised at least once in a test.  This means you need to write tests that exercise error conditions too.  Rule of thumb: one test method per expected outcome per method tested.  Have descriptive test method names.  Name the test class after the class being tested.
  • 14. TEST BASICS   Simply add ‘require_once PHPUnit/Autoload.php’ to each test file.  A PHPUnit test is a class that (usually) extends PHPUnit_Framework_TestCase.  The class name should end with the word ‘Test’, e.g. ‘FooBarTest’.  Each test class should be in its own file named after the class, e.g. ‘FooBarTest.php’.  Each test method name must begin with the word ‘test’, e.g. ‘testSomethingWorks’ or have an @test annotation.  Test methods must be public.  The class must contain one or more methods that perform tests or the test case will fail.  A test method must contain one or more assertions, be marked as incomplete or skipped.
  • 15. TEST FIXTURES   A fixture in a test is something (usually an object) that you want to test.  Also known as System Under Test (SUT).  PHPUnit will set up fixtures for you if you add protected methods setUp and optionally tearDown in your test class.  You provide code to create/destroy fixtures in these methods.  These methods are called before and after each test method so that each test runs on fresh fixtures.  setUpBeforeClass and tearDownAfterClass are also available. These are run once at the beginning and end of the test class.
  • 16. WRITING ASSERTIONS   Assertions are used to test expected behaviour from your SUT.  PHPUnit provides many different assertions for all sorts of needs, e.g. assertEquals, assertEmpty, assertTrue, assertType, et c.  You can also test output using expectOutputString.  More complicated assertions can be constructed using assertThat.  For a test to pass all assertions must evaluate to true.
  • 17. ANNOTATIONS   PHPUnit supports annotations to give instructions to the test method being executed.  Annotations are included in block comments before the method and always begin with an ‘@’.  Examples: @depends, @expectedException, @dataProvider.  Full details on supported annotations at http://www.phpunit.de/manual/3.6/en/appendix es.annotations.html
  • 18. DATA PROVIDERS   A data provider is a method that returns an array of values to use in a test.  PHPUnit will call the related test method once for each set of data, passing the values as arguments to the method.  Set using the @dataProvider annotation.  Allows you to easily add extra values to test with.  Also makes tests shorter and more concise by keeping values to test with out of test methods.
  • 19. TESTING EXCEPTIONS   You can tell PHPUnit that a test should expect an exception.  This can be done in two ways:  Through the method setExpectedException($exception, $message = ‘’, $code = null)  Through @expectedException, @expectedExceptionMessage, @e xpectedExceptionCode annotations.  PHP errors such as warnings are converted into exceptions by PHPUnit. These can also be tested for.
  • 20. MOCK OBJECTS  One of the most powerful features of PHPUnit.
  • 21. WTF IS A MOCK OBJECT?   Allows you to replace a dependency of your SUT with an object that has predefined behaviour.  The mock object becomes part of the test. If the methods defined are not called as expected the test fails.  Proper use of mock objects allow you to make sure you’re only testing the SUT and not other code.  Helps to ensure that if a test fails it’s in the SUT, not a dependency.  However, you need to be using Dependency Injection to use mock objects.
  • 22. MOCK OBJECT BASICS   PHPUnit creates a mock by sub-classing the original object.  Once you have a mock object you can define what methods you expect to be called on it, with what arguments and what the mock should do.
  • 23. OTHER MOCK OBJECT USES   Mock objects allow you to test concrete methods of abstract classes with getMockForAbstractClass.  You can create a mock object representing a SOAP web service using getMockFromWsdl.  PHPUnit has experimental support for mocking out file system calls using the package vfsStream.  More information at http://www.phpunit.de/manual/3.6/en/test- doubles.html.
  • 25. COMMAND LINE RUNNER   Tests are normally run from the command line with the phpunit command.  Just typing phpunit will get a ‘help’ output.  Passing the name of the test will run just that test.  You can also pass a path to a directory to run all tests in it or the name of a test file to run tests in that file.  PHPUnit prints a ‘.’ for each test passed, ‘F’ for a failure, ‘E’ for an error, ‘I’ for incomplete or ‘S’ for skipped.  More information is also printed for anything other than a pass.
  • 26. SAMPLE COMMAND LINE OUTPUT 
  • 27. OTHER WAYS TO RUN TESTS   Many IDE’s such as Zend Studio include PHPUnit integration. This enables you to write and run tests from within the IDE.  Running tests can be integrated into continuous integration servers such as Jenkins.  In this case your full test suite can be run automatically with each edit to your code.  Any test failure will mean the build fails.
  • 28. CODE COVERAGE ANALYSIS…  or how to make sure you’re not feeling a false sense of security.
  • 29. WTF IS CODE COVERAGE?   Code coverage tells you how much of your code is covered by tests.  PHPUnit can generate code coverage reports in a number of formats including HTML but…  You must have installed xDebug. (pecl install xdebug)  Helps to avoid a false sense of security.  Code coverage threshold percentage can be added to continuous integration builds.  Add code coverage by passing the –coverage-xxx option, eg. phpunit –coverage-html ./reports ./
  • 30. PHPUNIT TEST EXTENSIONS  Writing tests for different situations.
  • 31. INTRO TO EXTENSIONS   PHPUnit supports a number of extensions that allow you to write specialised tests.  These include working with databases, Selenium, and running profiling with XHProf.  Full details at http://www.phpunit.de/manual/3.6/en/installatio n.html.
  • 32. TESTING WITH DATABASES   To do this install the DbUnit  You need to provide a extension, eg. ‘pear install schema with tables for phpunit/DbUnit’ PHPUnit to use.  However, where possible  getConnection must return a PDO instance for PHPUnit avoid tests using a database to use. by using mock objects.  getDataSet returns data to  Test case must extend populate database tables ‘PHPUnit_Extensions_Datab with. ase_TestCase’.  PHPUnit truncates tables  Defines two extra methods before each test run and that you must implement: inserts data. This means getConnection and each test runs with a fresh set of predictable data. getDataSet.
  • 34. ADDING A CONFIG FILE   Options can be passed to PHPUnit through the command line but it also supports adding an XML config file.  This can include a number of options such as where to find test cases and which directories to include for code coverage analysis.  To use this just create the file and name it phpunit.xml, adding it to the root of your tests directory.  Especially useful when running tests as part of a CI build.  Full details at http://www.phpunit.de/manual/3.6/en/appendixes.co nfiguration.html
  • 35. LET’S WRITE SOME TESTS! 
  • 36. QUESTIONS?

Hinweis der Redaktion

  1. Ask who has written tests before. Ask about experience with PHPUnit.
  2. Single Responsibility PrincipleOpen/Closed PrincipleLiskov Substitution PrincipleInterface Segregation PrincipleDependency Inversion Principle
  3. Emphasise that it is a framework like other frameworks. You still need to write the 20% to have your own tests!
  4. Discuss that this only works if the pear command has been added to your path.
  5. Mention that the require_once call will only work if the path to the pear installation dir has been added to PHP’s include path.Mention that casing is important. Also mention that defaults (use of word test, etc) can be overridden in config, command line switches, etc.Mention that you can have as many methods as you like in a test class but only test* methods will be run as tests.
  6. Mention cases where setUpBeforeClass and tearDownAfterClass are useful.
  7. Mention annotations similar to doc blox in PHP.
  8. Explain that fatal errors cannot be converted to exceptions. Give an example where a warning could be caught, such as a call to fopen that fails on a non-existent file. Explain that PHPUnit registers its own error handler.
  9. Switch to browser to show sample code coverage report.
  10. Mention supported formats of data such as CSV and XML.