SlideShare una empresa de Scribd logo
1 de 20
Descargar para leer sin conexión
PHP Tests tips
How not to shoot yourself in the foot?

            Damian Sromek
            damiansromek.pl
               2012-06
Agenda
● What's about those tests?
● What are the tests about?
● What to do and not to do?
Test types
1. Acceptance (end-to-end)
   Test as if end user would use the whole
   system/feature.
2. Integration
   Test how different parts of system work
   together - eg. couple of classes or your class
   using some web service
3. Unit
   Test single unit (eg. class). Mock all
   dependencies, eg. web service, file system.
Tests will save you time & troubles
1. Prove you've done your work
2. Help you check much faster if you're work is
   done
3. Protect you from breaking things - regresion
4. Help you make better code design - easier to
   maintain
5. Let you apply changes with less worries -
   refactoring will improve things without
   breaking anything
How to be happy about tests?
1. If you're new to testing try with writing tests
   after writing the code
2. Once you're confident about testing try to
   write tests before the code - TDD
3. Start with acceptance tests, than integration
   and unit tests when your functionality is
   implemented
4. Run tests often - after every change and
   before any commit
5. Use continuous integration server
You will regret you've got a lot of
tests if you:
1. make them complex and hard to read
2. duplicate the test code
3. do not use descriptive fail messages
4. do not run them often - eg. you don't have
   continuous integration server
5. do not make them run fast
Behavioral tests
Draft - Behat
Feature: Log in and use the application
  In order to use the application
  As a user
  I need to log in using my smart card

@javascript
Scenario: Log in with inactive smart card
  Given I am inactive smart card user
  Given I am on "http://localhost/somethign.cool.php"
  When I log in
  Then I should see log in error message
What's good test like?
1. Finds as much bugs as possible
2. Tells you what the software can do and how
   to use it
3. Is easy to maintain
4. Independent from other tests and repeatable
How to start testing?
1. Write acceptance test for functionality you're
   implementing - it should cover main story
   flow
2. Make the test show meaningful fail message
3. Implement functionality so the test is passing
4. Add tests covering more story flows
5. Improve functionality code so all tests are
   passing again
6. Refactor (also tests)
7. Enjoy!
How to start even better?
1.   "Wait" for a bug
2.   Write a test confirming/reproducing that bug
3.   Fix the code using the test you've got
4.   Enjoy!
TDD flow
Repeat this process
1. Write test
2. Make test failure message descriptive and
   easy to understand
3. Make the test pass - implement feature
   you've write the test for
4. Refactor
Do not - test something irrelevant
<?php


// SHOULD TEST PLUGIN BUT IS TESTING DATABASE MODEL AND NOTHING MORE


class Plugin_Smooth_Streaming_BoundariesTest extends TestCase_Plugin
{
    ...


    public function testLowerBoundary()
    {
          $settings = Xstream_Loader::getModelHelper("SettingHelper");
          $lowerLimit = $settings->setSetting('plugin_boundaries', 'lower_limit',1.0);


          $this->assertEquals(1.0, $settings->getSetting('plugin_boundaries', 'lower_limit')->value);
    }


    ...


}
Do not - test too much at once
<?php
// TRY NOT TO MAKE MORE THAN 2-3 ASSERTIONS IN ONE TEST
class ResponseSetTest extends PHPUnit_Framework_TestCase
{
    ...
    public function testAddItems()
    {
          $responseSet = new Xs_Monitor_Response_Set('test');
          $this->assertEquals(Xs_Monitor_Interface::STATE_WARNING, $responseSet->getStateAsInteger());


          $responseSet->addResponse(new Xs_Monitor_Response('service 1', Xs_Monitor_Interface::STATE_OK, 'detail of service 1'));
          $this->assertEquals(Xs_Monitor_Interface::STATE_OK, $responseSet->getStateAsInteger());
          $this->assertNotEquals('detail of service 1', $responseSet->getDetails());


          $responseSet->addResponse(new Xs_Monitor_Response('service 2', 3, 'detail of service 2'));
          $this->assertEquals(3, $responseSet->getStateAsInteger());
          $this->assertEquals('UNKNOWN', $responseSet->getState());
          $this->assertEquals('detail of service 2', $responseSet->getDetails());


          $responseSet
            ->addResponse(new Xs_Monitor_Response('service 3', Xs_Monitor_Interface::STATE_WARNING, 'detail of service 3'));
          $this->assertEquals(Xs_Monitor_Interface::STATE_WARNING, $responseSet->getStateAsInteger());
          $this->assertEquals('detail of service 3', $responseSet->getDetails());


          $responseSet
            ->addResponse(new Xs_Monitor_Response('service 4', Xs_Monitor_Interface::STATE_CRITICAL, 'detail of service 4'));
          $this->assertEquals(Xs_Monitor_Interface::STATE_CRITICAL, $responseSet->getStateAsInteger());
          $this->assertEquals('detail of service 4', $responseSet->getDetails());


          $responseSet
            ->addResponse(new Xs_Monitor_Response('service 5', Xs_Monitor_Interface::STATE_CRITICAL, 'detail of service 5'));
          $this->assertEquals(Xs_Monitor_Interface::STATE_CRITICAL, $responseSet->getStateAsInteger());
          $this->assertEquals('detail of service 4', $responseSet->getDetails());
Do - use meaningful test name
Test name should be descriptive even if it has
very long name.
Try to avoid test names like "testAdd" etc.
Better would be something like
"testAddWillPutNewItemIntoContainer" or
"testAddWillThrowExceptionIfContainerIsFull"
 /**
  * @test
  */
 public function add()
 {
     ...
Do - use data providers
<?php


namespace XsTestUnit;


class StringTest extends TestCase
{


    /**
     * @param string $heystack
     * @param string $needle
     * @param boolean $expected
     *
     * @dataProvider endsWithDataProvider
     */

    public function testEndsWith($heystack, $needle, $expected)
    {
        $this->assertEquals($expected, XsString::endsWith($heystack, $needle));
    }


    public function endsWithDataProvider()
    {
        return array(
           array('asdf',   'f', true),
           array('asdf',   'df', true),
           array('asdf',   'asdf', true),
           array('asdf',   'd', false),
           array('asdf',   'xf', false),
           array('asdf',   'asd', false),
        );
    }

}
Do - test one unit in unit test
Unit test should NOT:
1. Test more than one unit/class
2. Touch database, filesystem,
   API/WebService etc. - you should mock all
   "externals"
3. Execute very fast - matter of 10th of second
Do - make tests easy to read and
understand
class Acceptance_Product_ProductListTest extends Test_TestCase
{
    public function testReturnsErrorAboutNoProductsUserCanBuyWhenHeHasNoProductsRelatedToMedia()
    {
        $this->user()
          ->logIn()
          ->withoutProducts(array(
             $this->svodProductId,
             $this->premiumSvodProductId
          ))
          ->withoutOrderedMedia($this->mediaId);

        $this->shop()->respondsJsonAboutNoProductsAvailable($this->mediaId);
    }
Do - make tests easy to read and
understand (2)
Draft
class SortingTest extends XsCanalDigitalTestStbAdbTestCase
{

    /**
     * @test
     */
    public function mediaListWithoutFixedSortingCanBeSortedByPressingRedButton()
    {
        $this->user()
             ->onPage($this->stbApp()->page('sort_fixed'));


        $initialAppState = $this->stbApp()->getState('maincovers');

        $this->user()->pressedButton(Key::BUTTON_RED);

        $appStateAfterPressingRedButton = $this->stbApp()->getState('maincovers');
        // TODO: better way of comparing items sorting
        $this->assertNotEquals(
              $initialAppState,
              $appStateAfterPressingRedButton,
             'Pressing red button should change page sorting'
        );
    }
Summary
1. Use TDD
2. Unit tests should test what you've written /
   proper unit and nothing more
3. Do not test too much in one test
4. Make your tests easy to maintain - proper
   naming etc.
5. Try to use data provider to test a lot of
   different cases without code duplication
Thank you
@see Test Driven Development
@see PHPUnit
@see Behavioral Driven Development
@see Behat

@see Growing Object-Oriented Software,
Guided by Tests
@see www.jenkins-ci.org

Más contenido relacionado

La actualidad más candente

DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing trainingTom Tang
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
 
Refactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGRefactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGLuca Minudel
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yiimadhavi Ghadge
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best PracticesTomaš Maconko
 
Introducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationIntroducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationTechWell
 
Fitnesse - Acceptance testing
Fitnesse - Acceptance testingFitnesse - Acceptance testing
Fitnesse - Acceptance testingvijay_challa
 
Programming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStringsProgramming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStringsAlan Richardson
 
Impact Analysis - LoopConf
Impact Analysis - LoopConfImpact Analysis - LoopConf
Impact Analysis - LoopConfChris Lema
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven TestingMaveryx
 
Acceptance & Functional Testing with Codeception - Devspace 2015
Acceptance & Functional Testing with Codeception - Devspace 2015 Acceptance & Functional Testing with Codeception - Devspace 2015
Acceptance & Functional Testing with Codeception - Devspace 2015 Joe Ferguson
 
Creating testing tools to support development
Creating testing tools to support developmentCreating testing tools to support development
Creating testing tools to support developmentChema del Barco
 
Codeception presentation
Codeception presentationCodeception presentation
Codeception presentationAndrei Burian
 
Real Life Unit Testing
Real Life Unit TestingReal Life Unit Testing
Real Life Unit TestingDror Helper
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done RightBrian Fenton
 

La actualidad más candente (20)

DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
Refactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGRefactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENG
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yii
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
 
Introducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationIntroducing Keyword-driven Test Automation
Introducing Keyword-driven Test Automation
 
Fitnesse - Acceptance testing
Fitnesse - Acceptance testingFitnesse - Acceptance testing
Fitnesse - Acceptance testing
 
Programming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStringsProgramming katas for Software Testers - CounterStrings
Programming katas for Software Testers - CounterStrings
 
Impact Analysis - LoopConf
Impact Analysis - LoopConfImpact Analysis - LoopConf
Impact Analysis - LoopConf
 
The Testing Planet - July 2010
The Testing Planet - July 2010The Testing Planet - July 2010
The Testing Planet - July 2010
 
Selenium Frameworks
Selenium FrameworksSelenium Frameworks
Selenium Frameworks
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
 
Acceptance & Functional Testing with Codeception - Devspace 2015
Acceptance & Functional Testing with Codeception - Devspace 2015 Acceptance & Functional Testing with Codeception - Devspace 2015
Acceptance & Functional Testing with Codeception - Devspace 2015
 
Creating testing tools to support development
Creating testing tools to support developmentCreating testing tools to support development
Creating testing tools to support development
 
Codeception presentation
Codeception presentationCodeception presentation
Codeception presentation
 
Real Life Unit Testing
Real Life Unit TestingReal Life Unit Testing
Real Life Unit Testing
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
PHPUnit - Unit testing
PHPUnit - Unit testingPHPUnit - Unit testing
PHPUnit - Unit testing
 
Testing 101
Testing 101Testing 101
Testing 101
 

Destacado

Continues Integration
Continues IntegrationContinues Integration
Continues IntegrationGreg Osuri
 
Continues Integration for Android
Continues Integration for AndroidContinues Integration for Android
Continues Integration for AndroidCODETE
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
Virtuális teamek
Virtuális teamekVirtuális teamek
Virtuális teamekpeterhari
 
Ejercicios de visual
Ejercicios de visualEjercicios de visual
Ejercicios de visualmagda_chivas_
 
Jamie Bergsman Powerpoint
Jamie Bergsman PowerpointJamie Bergsman Powerpoint
Jamie Bergsman Powerpointbergsmanj
 
A comparative look at development-oriented degrees in the St. Cloud Area
A comparative look at development-oriented degrees in the St. Cloud AreaA comparative look at development-oriented degrees in the St. Cloud Area
A comparative look at development-oriented degrees in the St. Cloud Areastephen.woods
 
Ejercicios de visual
Ejercicios de visualEjercicios de visual
Ejercicios de visualmagda_chivas_
 
Salesforce Mobile Developer Week Meetup karachi
Salesforce Mobile Developer Week Meetup karachiSalesforce Mobile Developer Week Meetup karachi
Salesforce Mobile Developer Week Meetup karachiMuhammad Salman Zafar
 
1st karachi salesforce platform dug meetup
1st karachi salesforce platform dug meetup1st karachi salesforce platform dug meetup
1st karachi salesforce platform dug meetupMuhammad Salman Zafar
 
Apresentação de bijuterias
Apresentação de bijuteriasApresentação de bijuterias
Apresentação de bijuteriasPatyBijus
 
Blog Pro 2.0 User Guide
Blog Pro 2.0 User GuideBlog Pro 2.0 User Guide
Blog Pro 2.0 User GuideIgor Goltsov
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2
Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2
Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2Muhammad Iqbal
 

Destacado (20)

Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016
 
Continues Integration
Continues IntegrationContinues Integration
Continues Integration
 
Continues Integration for Android
Continues Integration for AndroidContinues Integration for Android
Continues Integration for Android
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Fetus
FetusFetus
Fetus
 
Virtuális teamek
Virtuális teamekVirtuális teamek
Virtuális teamek
 
Ejercicios de visual
Ejercicios de visualEjercicios de visual
Ejercicios de visual
 
Jamie Bergsman Powerpoint
Jamie Bergsman PowerpointJamie Bergsman Powerpoint
Jamie Bergsman Powerpoint
 
Ford Field
Ford FieldFord Field
Ford Field
 
A comparative look at development-oriented degrees in the St. Cloud Area
A comparative look at development-oriented degrees in the St. Cloud AreaA comparative look at development-oriented degrees in the St. Cloud Area
A comparative look at development-oriented degrees in the St. Cloud Area
 
Ejercicios de visual
Ejercicios de visualEjercicios de visual
Ejercicios de visual
 
Ambito sociosanitario
Ambito sociosanitarioAmbito sociosanitario
Ambito sociosanitario
 
Salesforce Mobile Developer Week Meetup karachi
Salesforce Mobile Developer Week Meetup karachiSalesforce Mobile Developer Week Meetup karachi
Salesforce Mobile Developer Week Meetup karachi
 
1st karachi salesforce platform dug meetup
1st karachi salesforce platform dug meetup1st karachi salesforce platform dug meetup
1st karachi salesforce platform dug meetup
 
Apresentação de bijuterias
Apresentação de bijuteriasApresentação de bijuterias
Apresentação de bijuterias
 
Tulisan 1
Tulisan 1Tulisan 1
Tulisan 1
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
 
Blog Pro 2.0 User Guide
Blog Pro 2.0 User GuideBlog Pro 2.0 User Guide
Blog Pro 2.0 User Guide
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2
Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2
Buku iiia-borang-akreditasi-d4-pjj-2012 rev-copy2
 

Similar a Php tests tips

Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4Yi-Huan Chan
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in LaravelAhmed Yahia
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
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)
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Michelangelo van Dam
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-appsVenkata Ramana
 
Test Drive Development in Ruby On Rails
Test Drive Development in Ruby On RailsTest Drive Development in Ruby On Rails
Test Drive Development in Ruby On RailsNyros Technologies
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 

Similar a Php tests tips (20)

Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Clean tests good tests
Clean tests   good testsClean tests   good tests
Clean tests good tests
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in Laravel
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
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
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
 
Test Drive Development in Ruby On Rails
Test Drive Development in Ruby On RailsTest Drive Development in Ruby On Rails
Test Drive Development in Ruby On Rails
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 

Último

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 

Último (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 

Php tests tips

  • 1. PHP Tests tips How not to shoot yourself in the foot? Damian Sromek damiansromek.pl 2012-06
  • 2. Agenda ● What's about those tests? ● What are the tests about? ● What to do and not to do?
  • 3. Test types 1. Acceptance (end-to-end) Test as if end user would use the whole system/feature. 2. Integration Test how different parts of system work together - eg. couple of classes or your class using some web service 3. Unit Test single unit (eg. class). Mock all dependencies, eg. web service, file system.
  • 4. Tests will save you time & troubles 1. Prove you've done your work 2. Help you check much faster if you're work is done 3. Protect you from breaking things - regresion 4. Help you make better code design - easier to maintain 5. Let you apply changes with less worries - refactoring will improve things without breaking anything
  • 5. How to be happy about tests? 1. If you're new to testing try with writing tests after writing the code 2. Once you're confident about testing try to write tests before the code - TDD 3. Start with acceptance tests, than integration and unit tests when your functionality is implemented 4. Run tests often - after every change and before any commit 5. Use continuous integration server
  • 6. You will regret you've got a lot of tests if you: 1. make them complex and hard to read 2. duplicate the test code 3. do not use descriptive fail messages 4. do not run them often - eg. you don't have continuous integration server 5. do not make them run fast
  • 7. Behavioral tests Draft - Behat Feature: Log in and use the application In order to use the application As a user I need to log in using my smart card @javascript Scenario: Log in with inactive smart card Given I am inactive smart card user Given I am on "http://localhost/somethign.cool.php" When I log in Then I should see log in error message
  • 8. What's good test like? 1. Finds as much bugs as possible 2. Tells you what the software can do and how to use it 3. Is easy to maintain 4. Independent from other tests and repeatable
  • 9. How to start testing? 1. Write acceptance test for functionality you're implementing - it should cover main story flow 2. Make the test show meaningful fail message 3. Implement functionality so the test is passing 4. Add tests covering more story flows 5. Improve functionality code so all tests are passing again 6. Refactor (also tests) 7. Enjoy!
  • 10. How to start even better? 1. "Wait" for a bug 2. Write a test confirming/reproducing that bug 3. Fix the code using the test you've got 4. Enjoy!
  • 11. TDD flow Repeat this process 1. Write test 2. Make test failure message descriptive and easy to understand 3. Make the test pass - implement feature you've write the test for 4. Refactor
  • 12. Do not - test something irrelevant <?php // SHOULD TEST PLUGIN BUT IS TESTING DATABASE MODEL AND NOTHING MORE class Plugin_Smooth_Streaming_BoundariesTest extends TestCase_Plugin { ... public function testLowerBoundary() { $settings = Xstream_Loader::getModelHelper("SettingHelper"); $lowerLimit = $settings->setSetting('plugin_boundaries', 'lower_limit',1.0); $this->assertEquals(1.0, $settings->getSetting('plugin_boundaries', 'lower_limit')->value); } ... }
  • 13. Do not - test too much at once <?php // TRY NOT TO MAKE MORE THAN 2-3 ASSERTIONS IN ONE TEST class ResponseSetTest extends PHPUnit_Framework_TestCase { ... public function testAddItems() { $responseSet = new Xs_Monitor_Response_Set('test'); $this->assertEquals(Xs_Monitor_Interface::STATE_WARNING, $responseSet->getStateAsInteger()); $responseSet->addResponse(new Xs_Monitor_Response('service 1', Xs_Monitor_Interface::STATE_OK, 'detail of service 1')); $this->assertEquals(Xs_Monitor_Interface::STATE_OK, $responseSet->getStateAsInteger()); $this->assertNotEquals('detail of service 1', $responseSet->getDetails()); $responseSet->addResponse(new Xs_Monitor_Response('service 2', 3, 'detail of service 2')); $this->assertEquals(3, $responseSet->getStateAsInteger()); $this->assertEquals('UNKNOWN', $responseSet->getState()); $this->assertEquals('detail of service 2', $responseSet->getDetails()); $responseSet ->addResponse(new Xs_Monitor_Response('service 3', Xs_Monitor_Interface::STATE_WARNING, 'detail of service 3')); $this->assertEquals(Xs_Monitor_Interface::STATE_WARNING, $responseSet->getStateAsInteger()); $this->assertEquals('detail of service 3', $responseSet->getDetails()); $responseSet ->addResponse(new Xs_Monitor_Response('service 4', Xs_Monitor_Interface::STATE_CRITICAL, 'detail of service 4')); $this->assertEquals(Xs_Monitor_Interface::STATE_CRITICAL, $responseSet->getStateAsInteger()); $this->assertEquals('detail of service 4', $responseSet->getDetails()); $responseSet ->addResponse(new Xs_Monitor_Response('service 5', Xs_Monitor_Interface::STATE_CRITICAL, 'detail of service 5')); $this->assertEquals(Xs_Monitor_Interface::STATE_CRITICAL, $responseSet->getStateAsInteger()); $this->assertEquals('detail of service 4', $responseSet->getDetails());
  • 14. Do - use meaningful test name Test name should be descriptive even if it has very long name. Try to avoid test names like "testAdd" etc. Better would be something like "testAddWillPutNewItemIntoContainer" or "testAddWillThrowExceptionIfContainerIsFull" /** * @test */ public function add() { ...
  • 15. Do - use data providers <?php namespace XsTestUnit; class StringTest extends TestCase { /** * @param string $heystack * @param string $needle * @param boolean $expected * * @dataProvider endsWithDataProvider */ public function testEndsWith($heystack, $needle, $expected) { $this->assertEquals($expected, XsString::endsWith($heystack, $needle)); } public function endsWithDataProvider() { return array( array('asdf', 'f', true), array('asdf', 'df', true), array('asdf', 'asdf', true), array('asdf', 'd', false), array('asdf', 'xf', false), array('asdf', 'asd', false), ); } }
  • 16. Do - test one unit in unit test Unit test should NOT: 1. Test more than one unit/class 2. Touch database, filesystem, API/WebService etc. - you should mock all "externals" 3. Execute very fast - matter of 10th of second
  • 17. Do - make tests easy to read and understand class Acceptance_Product_ProductListTest extends Test_TestCase { public function testReturnsErrorAboutNoProductsUserCanBuyWhenHeHasNoProductsRelatedToMedia() { $this->user() ->logIn() ->withoutProducts(array( $this->svodProductId, $this->premiumSvodProductId )) ->withoutOrderedMedia($this->mediaId); $this->shop()->respondsJsonAboutNoProductsAvailable($this->mediaId); }
  • 18. Do - make tests easy to read and understand (2) Draft class SortingTest extends XsCanalDigitalTestStbAdbTestCase { /** * @test */ public function mediaListWithoutFixedSortingCanBeSortedByPressingRedButton() { $this->user() ->onPage($this->stbApp()->page('sort_fixed')); $initialAppState = $this->stbApp()->getState('maincovers'); $this->user()->pressedButton(Key::BUTTON_RED); $appStateAfterPressingRedButton = $this->stbApp()->getState('maincovers'); // TODO: better way of comparing items sorting $this->assertNotEquals( $initialAppState, $appStateAfterPressingRedButton, 'Pressing red button should change page sorting' ); }
  • 19. Summary 1. Use TDD 2. Unit tests should test what you've written / proper unit and nothing more 3. Do not test too much in one test 4. Make your tests easy to maintain - proper naming etc. 5. Try to use data provider to test a lot of different cases without code duplication
  • 20. Thank you @see Test Driven Development @see PHPUnit @see Behavioral Driven Development @see Behat @see Growing Object-Oriented Software, Guided by Tests @see www.jenkins-ci.org