SlideShare ist ein Scribd-Unternehmen logo
1 von 80
Developer Testing 101
Goals


• Learn what is Developer Testing
• Gain confidence in writing tests with an
  xUnit Testing Framework
Non-Goals

• When to test with external
  dependencies, ie. databases
• Not to necessarily learn how to write
  the best (code) tests
Resources

Code Samples
   https://github.etsycorp.com/llincoln/
   DeveloperTesting101

PHPUnit Manual
   http://www.phpunit.de/manual/current/en/

PHPUnit GitHub
   https://github.com/sebastianbergmann/phpunit

Etsy PHPUnit Extensions
   https://github.com/etsy/phpunit-extensions/wiki
Topics
• Methodology, Terminology, Kool-Aid
• xUnit Basics and Theory
• Assertions
• Data Driven Tests
• Test Classification
• Stubs, Fakes, and Mocks
• Methodology, Terminology, Kool-Aid
 • Agile
 • Test-Driven Development (TDD)
 • Pyramid of Testing
Agile
a·gil·i·ty [uh-jil-i-tee]
            



noun
1. the power of moving quickly and easily;
nimbleness: exercises demanding agility.
2. the ability to think and draw conclusions
quickly; intellectual acuity.
Agile Manifesto
• Individuals and interactions
 • over processes and tools
• Working software
 • over comprehensive documentation
• Customer collaboration
 • over contract negotiation
• Responding to change
 • over following a plan
TDD
TDD
Test Driven Development
Waterfall
The Assembly Line
TDD   Waterfall
Developer Testing
   TDD is a design process
Why Developer Testing?


 • Verify Correctness
 • Communication
 • Gain Confidence
Inside Out v. Outside In
Inside Out v. Outside In


 • Implement first     • Test first

 • Easy to code       • Easy to test

 • Difficult to test   • Easy to code
Tests should always be treated like every
other consumer of the subject under test.
Pyramid of Testing
Test Types
Vocabulary Break!
Functional Tests


Does the overall
product satisfy the
the requirements?
Integration Tests


Do the pieces fit
together?
Unit Tests


Is the logic correct in
that function?
Functional
Understand the product.
The Tools
The Tools


• BeHat (Cucumber)
The Tools


• BeHat (Cucumber)
• PHPSpec
The Tools


• BeHat (Cucumber)
• PHPSpec
• Keyboard, Mouse, and You
When Do They Work?

• During prototyping
• Focused on the product requirements
• Refactoring
• Regression of key features
• Better for smaller teams
...Stop Helping?


• Focused on the implementation
• Rapidly changing functionality
• Large organizations
After
Greenfield
Inverted Test Pyramid
Test Pyramid
Food Pyramid of the 90s
Unit Tests
Simple and to the point.
Verify Correctness


• Line coverage
• Branch coverage
• Icky Bits-o-Logic
Gain Confidence

• Individual functions
• Variety of parameters
• Works for expected interactions with
  collaborators
Communication

• Show how to use the function
• Show expected interactions with other
  collaborators
• Increase discoverability of possible
  reuse
Integration
For everything in-between.
You’re Paranoid

• Experimenting with third-party code or
  service
• You do not trust that your collaborators
  work as specified
Sorry! Piece of Testing
                 Functional


   Integration



                      Unit
• Methodology, Terminology, Kool-Aid
 • Agile for realz!
        Developer Testing
 • Test-Driven Development (TDD)
 Sorry! piece
 • Pyramid of Testing
xUnit Basics and Theory
TestCase

class My_Class { ... }


class My_ClassTest
extends PHPUnit_Framework_TestCase
{ ... }
testFunction
class My_Class {
    function foo(){ ... }
}


class My_ClassTest
extends PHPUnit_Framework_TestCase {
    function testFoo() { ... }
}
@test

class My_ClassTest
extends PHPUnit_Framework_TestCase {
    /**
     * @test
     */
    function foo() { ... }
}
Several Tests Per Function
  class My_Class {
      function foo(/*bool*/ $param){ ... }
  }
  class My_ClassTest
  extends PHPUnit_Framework_TestCase {
      function testFoo_true() { ... }
      function testFoo_false() { ... }
  }
xUnit Basics
• HappySet
• 01-xUnitBasics
 • FlowTest.php
 • ChildTest.php -> ParentTest.php
 • UniqueInstanceTest.php
 • StaticTest.php
 • GlobalStateTest.php
 • TestListener.php and listener-
Honorable Mentions

• public static function
  setUpBeforeClass()
• public static function
  tearDownAfterClass()
• /** @depends */
Equivalence Class Partitioning
         A Little Math Lesson
Equivalence Relation

• Let S be any set and let ~ be a relation on S.
  Then ~ is called an equivalence relation
  provided it satisfies the following laws:
  •   Reflexive a ~ a

  •   Symmetrical a ~ b implies b ~ a

  •   Transitive a ~ b and b ~ c implies a ~ c
Partition


• A partition of a nonempty set S is a
  collection of nonempty subsets that are
  disjoint and whose union is S.
Equivalence Class

Consider again an equivalence relation ~ on a
set S. For each s in S we define
        [s] = {t ∈ S : s ~ t}

The set [s] is called the equivalence class
containing s.
Input
Partitioning
     Write just the
 right number of tests
ECP
• 02-ECP
 • Boolean.php
 • String.php
 • Integer.php
 • ControlStructures.php
 • Object.php
Assertions
Assertions

• 03-Assertions
 • StatusTest.php
 • AssertTest.php
 • ExceptionTest.php
Built-In Assertions
• assertArrayHasKey          • assertLessThanOrEqual
• assertContains             • assertNull
• assertContainsOnly         • assertRegExp
• assertCount                • assertStringMatchesFormat
• assertEmpty                • assertSame
• assertEquals               • assertStringStartsWith
• assertFalse                • assertStringEndsWith
• assertGreaterThan          • assertTag
• assertGreaterThanOrEqual   • assertThat
• assertInstanceOf           • assertTrue
• assertInternalType
• assertLessThan             • more...
Custom Asserts
• Work-around for multiple asserts

• No appropriate assert or constraint exists

• One of the few times statics aren’t so bad

• Consider writing a new
  PHPUnit_Framework_Constraint

• Use
        assertThat(
            mixed $value,
            PHPUnit_Framework_Constraint $constraint
            [, $message = ‘’]
        )
Data Driven Tests
Data Driven Testing

• 04-DataDrivenTesting
 • Calculator.php
 • CalculatorTest.php
 • DataDrivenTest.php
@dataProvider
    /**
     * @dataProvider <methodName>
     */


•   Provider method must be public
•   Return must be a double array
•   Cannot depend on instance variables
•   Always use literal values
Test Classification
External Dependencies

• Memcache
• MySQL
• Postgres
• Services via Network
More Sources of Flake


• Sleep
• Date/Time
• Random Number Generators
@group

• @group cache
 •   for test that use memcache
• @group dbunit
 •   for test that use DBUnit and databases
• @group network
 •   for tests that talk to external services
• @group flaky
 •   for tests that fail without a code change
Unit Tests are DEFAULT



   There is NO @group for unit tests.
Test Sizes

• New in PHPUnit 3.6
• @small run in less than one second
• @medium run in less than 10 seconds
• @large run in less than 60 seconds
• Note: All times are configurable
Stubs, Fakes, and Mocks
The Difference


• Stub returns fixed values
• Fake returns modifiable values
• Mock mimics the behavior of the original
Creating a Mock
        /**
     * Returns a mock object for the specified class.
     *
     * @param string $originalClassName
     * @param array    $methods
     * @param array    $arguments
     * @param string $mockClassName
     * @param boolean $callOriginalConstructor
     * @param boolean $callOriginalClone
     * @param boolean $callAutoload
     * @return PHPUnit_Framework_MockObject_MockObject
     * @throws InvalidArgumentException
     * @since Method available since Release 3.0.0
     */
    public function getMock($originalClassName, $methods = array(), array
$arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE,
$callOriginalClone = TRUE, $callAutoload = TRUE) { ... }
    
Mock Builder
$stub = $this->getMock(
    ‘SomeClass’, null, null, ‘’, false
);

                  or

$stub =
    $this->getMockBuilder(‘SomeClass’)
        ->disableOriginalConstructor()
        ->getMock();
Mock Builder Options
• setMethods(array|null $methods)
• setConstructorArgs(array|null
  $args)
• setMockClassName($name)
• disableOriginalConstructor()
• disableOriginalClone()
• disableAutoload()
expects()

• Takes a PHPUnit_Framework_MockObject_Matcher
 •   $this->any()
 •   $this->never()
 •   $this->once()
 •   $this->exactly(int $count)
 •   $this->at(int $index)
method()



• Simply takes the name of the method to stub/mock as
  a String
with()


• Takes a variable number of Strings or
  PHPUnit_Framework_Constraints
with()
•   equalTo()              •   identicalTo()
•   anything()             •   isInstanceOf()
•   isTrue()               •   isType()
•   isFalse()              •   matchesRegularExpression
•   isNull()               •   matches()
•   contains()             •   stringStartWith()
•   containsOnly()         •   stringEndWith()
•   arrayHasKey()          •   stringContains()
•   isEmpty()              •   logicalAnd()
•   greaterThan()          •   logicalOr()
•   greaterThanOrEqual()   •   logicalNot()
•   lessThan()             •   logicalXor()
•   lessThanOrEqual()      •   more...
will()
• Takes a PHPUnit_Framework_MockObject_Stub
  • $this->returnValue()
  • $this->returnArgument()
  • $this->returnSelf()
  • $this->returnValueMap()
  • $this->returnCallback()
  • $this->onConsecutiveCalls()
  • $this->throwsException()
Return Stub


• See an example of a
  PHPUnit_Framework_MockObject_Stub
  • etsy/phpunit-extensions
Stub (or Fake) in PHPUnit

$stub = $this->getMock(‘SomeClass’);

$stub
    ->expects($this->any())
    ->method(‘someMethod’)
    ->will($this->returnValue(2));
Mocks in PHPUnit

$mock = $this->getMock(‘SomeClass’);

$mock
    ->expects($this->any())
    ->method(‘someMethod’)
    ->with($this->greaterThan(2))
    ->will($this->returnValue(true));
Preview: Mockery
• Requires PHP 5.3
• More fluent PHPUnit Mocks
     •    expects->method->with->will

• Example
 use Mockery as m;


     class SimpleTest extends PHPUnit_Framework_TestCase {
        public function testSimpleMock() {
            $mock = m::mock('simple mock');
            $mock->shouldReceive('foo')->with(5, m::any())->once()->andReturn(10);
            $this->assertEquals(10, $mock->foo(5));
        }

         public function teardown() {
             m::close();
         }
 }

Weitere ähnliche Inhalte

Was ist angesagt?

Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Harry Potter
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
Wen-Tien Chang
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
Will Shen
 

Was ist angesagt? (15)

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
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10Php through the eyes of a hoster pbc10
Php through the eyes of a hoster pbc10
 
Java 104
Java 104Java 104
Java 104
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
 
Write code that writes code!
Write code that writes code!Write code that writes code!
Write code that writes code!
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 

Ähnlich wie Developer testing 101: Become a Testing Fanatic

Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010
Stephan Hochdörfer
 
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
Michelangelo van Dam
 

Ähnlich wie Developer testing 101: Become a Testing Fanatic (20)

Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to Integrate
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
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)
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Testing untestable code - DPC10
Testing untestable code - DPC10Testing untestable code - DPC10
Testing untestable code - DPC10
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublin
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
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
 
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
 
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
 
Learn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshopLearn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshop
 

Mehr von LB Denker

Testing and DevOps Culture: Lessons Learned
Testing and DevOps Culture: Lessons LearnedTesting and DevOps Culture: Lessons Learned
Testing and DevOps Culture: Lessons Learned
LB Denker
 
Php com con-2011
Php com con-2011Php com con-2011
Php com con-2011
LB Denker
 

Mehr von LB Denker (7)

Testing and DevOps Culture: Lessons Learned
Testing and DevOps Culture: Lessons LearnedTesting and DevOps Culture: Lessons Learned
Testing and DevOps Culture: Lessons Learned
 
Php|tek '12 It's More Than Just Style
Php|tek '12  It's More Than Just StylePhp|tek '12  It's More Than Just Style
Php|tek '12 It's More Than Just Style
 
phpDay 2012: Scaling Communication via Continuous Integration
phpDay 2012: Scaling Communication via Continuous IntegrationphpDay 2012: Scaling Communication via Continuous Integration
phpDay 2012: Scaling Communication via Continuous Integration
 
QC Merge 2012: Growing community
QC Merge 2012: Growing communityQC Merge 2012: Growing community
QC Merge 2012: Growing community
 
PHP UK Conference 2012: Scaling Communication via Continuous Integration
PHP UK Conference 2012: Scaling Communication via Continuous IntegrationPHP UK Conference 2012: Scaling Communication via Continuous Integration
PHP UK Conference 2012: Scaling Communication via Continuous Integration
 
Are Your Tests Really Helping You?
Are Your Tests Really Helping You?Are Your Tests Really Helping You?
Are Your Tests Really Helping You?
 
Php com con-2011
Php com con-2011Php com con-2011
Php com con-2011
 

Kürzlich hochgeladen

+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+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...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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​
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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, ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
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
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
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...
 
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 ...
 
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
 
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, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Developer testing 101: Become a Testing Fanatic

  • 2. Goals • Learn what is Developer Testing • Gain confidence in writing tests with an xUnit Testing Framework
  • 3. Non-Goals • When to test with external dependencies, ie. databases • Not to necessarily learn how to write the best (code) tests
  • 4. Resources Code Samples https://github.etsycorp.com/llincoln/ DeveloperTesting101 PHPUnit Manual http://www.phpunit.de/manual/current/en/ PHPUnit GitHub https://github.com/sebastianbergmann/phpunit Etsy PHPUnit Extensions https://github.com/etsy/phpunit-extensions/wiki
  • 5. Topics • Methodology, Terminology, Kool-Aid • xUnit Basics and Theory • Assertions • Data Driven Tests • Test Classification • Stubs, Fakes, and Mocks
  • 6. • Methodology, Terminology, Kool-Aid • Agile • Test-Driven Development (TDD) • Pyramid of Testing
  • 8. a·gil·i·ty [uh-jil-i-tee]   noun 1. the power of moving quickly and easily; nimbleness: exercises demanding agility. 2. the ability to think and draw conclusions quickly; intellectual acuity.
  • 9. Agile Manifesto • Individuals and interactions • over processes and tools • Working software • over comprehensive documentation • Customer collaboration • over contract negotiation • Responding to change • over following a plan
  • 10. TDD
  • 13. TDD Waterfall
  • 14. Developer Testing TDD is a design process
  • 15. Why Developer Testing? • Verify Correctness • Communication • Gain Confidence
  • 16. Inside Out v. Outside In
  • 17. Inside Out v. Outside In • Implement first • Test first • Easy to code • Easy to test • Difficult to test • Easy to code
  • 18. Tests should always be treated like every other consumer of the subject under test.
  • 21. Functional Tests Does the overall product satisfy the the requirements?
  • 22. Integration Tests Do the pieces fit together?
  • 23. Unit Tests Is the logic correct in that function?
  • 26. The Tools • BeHat (Cucumber)
  • 27. The Tools • BeHat (Cucumber) • PHPSpec
  • 28. The Tools • BeHat (Cucumber) • PHPSpec • Keyboard, Mouse, and You
  • 29. When Do They Work? • During prototyping • Focused on the product requirements • Refactoring • Regression of key features • Better for smaller teams
  • 30. ...Stop Helping? • Focused on the implementation • Rapidly changing functionality • Large organizations
  • 33. Unit Tests Simple and to the point.
  • 34. Verify Correctness • Line coverage • Branch coverage • Icky Bits-o-Logic
  • 35. Gain Confidence • Individual functions • Variety of parameters • Works for expected interactions with collaborators
  • 36. Communication • Show how to use the function • Show expected interactions with other collaborators • Increase discoverability of possible reuse
  • 38. You’re Paranoid • Experimenting with third-party code or service • You do not trust that your collaborators work as specified
  • 39. Sorry! Piece of Testing Functional Integration Unit
  • 40. • Methodology, Terminology, Kool-Aid • Agile for realz! Developer Testing • Test-Driven Development (TDD) Sorry! piece • Pyramid of Testing
  • 42. TestCase class My_Class { ... } class My_ClassTest extends PHPUnit_Framework_TestCase { ... }
  • 43. testFunction class My_Class { function foo(){ ... } } class My_ClassTest extends PHPUnit_Framework_TestCase { function testFoo() { ... } }
  • 44. @test class My_ClassTest extends PHPUnit_Framework_TestCase { /** * @test */ function foo() { ... } }
  • 45. Several Tests Per Function class My_Class { function foo(/*bool*/ $param){ ... } } class My_ClassTest extends PHPUnit_Framework_TestCase { function testFoo_true() { ... } function testFoo_false() { ... } }
  • 46. xUnit Basics • HappySet • 01-xUnitBasics • FlowTest.php • ChildTest.php -> ParentTest.php • UniqueInstanceTest.php • StaticTest.php • GlobalStateTest.php • TestListener.php and listener-
  • 47. Honorable Mentions • public static function setUpBeforeClass() • public static function tearDownAfterClass() • /** @depends */
  • 48. Equivalence Class Partitioning A Little Math Lesson
  • 49. Equivalence Relation • Let S be any set and let ~ be a relation on S. Then ~ is called an equivalence relation provided it satisfies the following laws: • Reflexive a ~ a • Symmetrical a ~ b implies b ~ a • Transitive a ~ b and b ~ c implies a ~ c
  • 50. Partition • A partition of a nonempty set S is a collection of nonempty subsets that are disjoint and whose union is S.
  • 51. Equivalence Class Consider again an equivalence relation ~ on a set S. For each s in S we define [s] = {t ∈ S : s ~ t} The set [s] is called the equivalence class containing s.
  • 52. Input Partitioning Write just the right number of tests
  • 53. ECP • 02-ECP • Boolean.php • String.php • Integer.php • ControlStructures.php • Object.php
  • 55. Assertions • 03-Assertions • StatusTest.php • AssertTest.php • ExceptionTest.php
  • 56. Built-In Assertions • assertArrayHasKey • assertLessThanOrEqual • assertContains • assertNull • assertContainsOnly • assertRegExp • assertCount • assertStringMatchesFormat • assertEmpty • assertSame • assertEquals • assertStringStartsWith • assertFalse • assertStringEndsWith • assertGreaterThan • assertTag • assertGreaterThanOrEqual • assertThat • assertInstanceOf • assertTrue • assertInternalType • assertLessThan • more...
  • 57. Custom Asserts • Work-around for multiple asserts • No appropriate assert or constraint exists • One of the few times statics aren’t so bad • Consider writing a new PHPUnit_Framework_Constraint • Use assertThat( mixed $value, PHPUnit_Framework_Constraint $constraint [, $message = ‘’] )
  • 59. Data Driven Testing • 04-DataDrivenTesting • Calculator.php • CalculatorTest.php • DataDrivenTest.php
  • 60. @dataProvider /** * @dataProvider <methodName> */ • Provider method must be public • Return must be a double array • Cannot depend on instance variables • Always use literal values
  • 62. External Dependencies • Memcache • MySQL • Postgres • Services via Network
  • 63. More Sources of Flake • Sleep • Date/Time • Random Number Generators
  • 64. @group • @group cache • for test that use memcache • @group dbunit • for test that use DBUnit and databases • @group network • for tests that talk to external services • @group flaky • for tests that fail without a code change
  • 65. Unit Tests are DEFAULT There is NO @group for unit tests.
  • 66. Test Sizes • New in PHPUnit 3.6 • @small run in less than one second • @medium run in less than 10 seconds • @large run in less than 60 seconds • Note: All times are configurable
  • 68. The Difference • Stub returns fixed values • Fake returns modifiable values • Mock mimics the behavior of the original
  • 69. Creating a Mock /** * Returns a mock object for the specified class. * * @param string $originalClassName * @param array $methods * @param array $arguments * @param string $mockClassName * @param boolean $callOriginalConstructor * @param boolean $callOriginalClone * @param boolean $callAutoload * @return PHPUnit_Framework_MockObject_MockObject * @throws InvalidArgumentException * @since Method available since Release 3.0.0 */     public function getMock($originalClassName, $methods = array(), array $arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) { ... }     
  • 70. Mock Builder $stub = $this->getMock( ‘SomeClass’, null, null, ‘’, false ); or $stub = $this->getMockBuilder(‘SomeClass’) ->disableOriginalConstructor() ->getMock();
  • 71. Mock Builder Options • setMethods(array|null $methods) • setConstructorArgs(array|null $args) • setMockClassName($name) • disableOriginalConstructor() • disableOriginalClone() • disableAutoload()
  • 72. expects() • Takes a PHPUnit_Framework_MockObject_Matcher • $this->any() • $this->never() • $this->once() • $this->exactly(int $count) • $this->at(int $index)
  • 73. method() • Simply takes the name of the method to stub/mock as a String
  • 74. with() • Takes a variable number of Strings or PHPUnit_Framework_Constraints
  • 75. with() • equalTo() • identicalTo() • anything() • isInstanceOf() • isTrue() • isType() • isFalse() • matchesRegularExpression • isNull() • matches() • contains() • stringStartWith() • containsOnly() • stringEndWith() • arrayHasKey() • stringContains() • isEmpty() • logicalAnd() • greaterThan() • logicalOr() • greaterThanOrEqual() • logicalNot() • lessThan() • logicalXor() • lessThanOrEqual() • more...
  • 76. will() • Takes a PHPUnit_Framework_MockObject_Stub • $this->returnValue() • $this->returnArgument() • $this->returnSelf() • $this->returnValueMap() • $this->returnCallback() • $this->onConsecutiveCalls() • $this->throwsException()
  • 77. Return Stub • See an example of a PHPUnit_Framework_MockObject_Stub • etsy/phpunit-extensions
  • 78. Stub (or Fake) in PHPUnit $stub = $this->getMock(‘SomeClass’); $stub ->expects($this->any()) ->method(‘someMethod’) ->will($this->returnValue(2));
  • 79. Mocks in PHPUnit $mock = $this->getMock(‘SomeClass’); $mock ->expects($this->any()) ->method(‘someMethod’) ->with($this->greaterThan(2)) ->will($this->returnValue(true));
  • 80. Preview: Mockery • Requires PHP 5.3 • More fluent PHPUnit Mocks • expects->method->with->will • Example use Mockery as m; class SimpleTest extends PHPUnit_Framework_TestCase { public function testSimpleMock() { $mock = m::mock('simple mock'); $mock->shouldReceive('foo')->with(5, m::any())->once()->andReturn(10); $this->assertEquals(10, $mock->foo(5)); } public function teardown() { m::close(); } }

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n