SlideShare a Scribd company logo
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();
         }
 }

More Related Content

What's hot

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
Ram 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 PHPUnit
Michelangelo 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 2015
CiaranMcNulty
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
Suraj Deshmukh
 
TDD Training
TDD TrainingTDD Training
TDD Training
Manuela Grindei
 
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
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
Lean Teams Consultancy
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Harry 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 pbc10
Combell NV
 
Java 104
Java 104Java 104
Java 104
Manuela Grindei
 
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
Colin 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 Testing
Mike 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
 

What's hot (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 to 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 Integrate
LB 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] 2023
Mark 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 2022
Mark 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 Structure
Salesforce Developers
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
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
Michelangelo van Dam
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
Hendrik Ebbers
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
Mindfire 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 2014
FalafelSoftware
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
Thanh 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 Zendcon09
Michelangelo 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 Structure
CRMScienceKirk
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
Mark 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 tek12
Michelangelo 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 development
Stephen 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 workshop
chartjes
 

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

More from 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 Style
LB 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 Integration
LB Denker
 
QC Merge 2012: Growing community
QC Merge 2012: Growing communityQC Merge 2012: Growing community
QC Merge 2012: Growing community
LB 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 Integration
LB 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
 

More from 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
 

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 

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

Editor's Notes

  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