SlideShare una empresa de Scribd logo
1 de 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();
         }
 }

Más contenido relacionado

La actualidad más candente

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
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitMichelangelo van Dam
 
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 2015CiaranMcNulty
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
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 RubyWen-Tien Chang
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
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 pbc10Combell NV
 
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/2017Colin Oakley
 
Write code that writes code!
Write code that writes code!Write code that writes code!
Write code that writes code!Jason Feinstein
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit TestingWen-Tien Chang
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 

La actualidad más candente (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
 

Similar a Developer testing 101: Become a Testing Fanatic

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 IntegrateLB Denker
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Mark Niebergall
 
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
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Mark Niebergall
 
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 StructureSalesforce Developers
 
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 - phpdublinMichelangelo van Dam
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
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 2014FalafelSoftware
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Stephan Hochdörfer
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09Michelangelo van Dam
 
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 StructureCRMScienceKirk
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the UntestableMark Baker
 
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
 
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
 
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
 
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 workshopchartjes
 

Similar a 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
 

Más de LB Denker

Testing and DevOps Culture: Lessons Learned
Testing and DevOps Culture: Lessons LearnedTesting and DevOps Culture: Lessons Learned
Testing and DevOps Culture: Lessons LearnedLB Denker
 
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 StyleLB Denker
 
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 IntegrationLB Denker
 
QC Merge 2012: Growing community
QC Merge 2012: Growing communityQC Merge 2012: Growing community
QC Merge 2012: Growing communityLB Denker
 
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 IntegrationLB Denker
 
Are Your Tests Really Helping You?
Are Your Tests Really Helping You?Are Your Tests Really Helping You?
Are Your Tests Really Helping You?LB Denker
 
Php com con-2011
Php com con-2011Php com con-2011
Php com con-2011LB Denker
 

Más de 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
 

Último

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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(); } }

Notas del editor

  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