SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Test in Action – Week 3
      Stub / Mock
      Hubert Chan
Back to Basics
• Wikipedia said unit testing is
  – A software verification and validation method in
    which a programmer tests if individual units of
    source code are fit for use.
Dependency in the Test
• System Under Test (SUT) Dependency
  – SUT need another module to perform its task
     • Handler need a $dbmodel to perform query
     • $handler = new Handler($dbmodel);
Real Object is Hard to Test
• Real object
  – Supplies non-deterministic results
     • (e.g. the current temperature)
  – Difficult to create or reproduce (e.g. network fail)
  – Slow (e.g. database)
  – Does not yet exist or may change behavior
Substitute Dependency
• Using Fake
  – Fake is anything not real
• Fake techniques
  – Mock object
  – Stub object
  – Fake object
Stub Objects
• Stub Objects
  – Stubs provide canned answers to calls made
    during the test
  – Usually not responding at all to anything outside
    what's programmed in for the test
Fake Objects
• Fake Objects
  – Fake objects have working implementations
  – Usually take some shortcut, which makes them
    not suitable for production.
  – Example
     • An in-memory file system
     • An in-memory registry manager
Example: AlertSystem
Example: AlertSystem
• Component Overview
  – AlertSystem
     • Send notification to the targets, such as e-mail or SMS
       notifier.
  – NotifierInterface instance
     • Send actually notification to the target
  – NotifierTargetProviderInterface instance
     • Provide a target array to send notification
AlertSystem Test
• Dependency Analysis
  – Collaboration Classes
     • NotifierInterface
     • NotifierTargetProviderInterface

• Tests should
  – Only focus on AlertSystem
  – Fake the dependency
Make a Fake?
• FileNotifyTargetProvider
class FileNotifyTargetProvider
    implements NotifyTargetProviderInterface {

    function __construct($filename) {
        $this->_filename = $filename;
    }

    public function get_targets() {
        $targets = array();
        $handle = @fopen($this->_filename, "r");

        while (($target = fgets($handle)) !== FALSE) {
            $targets[] = $target;
        }
        return $targets;
    }
}
Make a Stub?
• StubNotifier
class StubNotifier implements NotifierInterface {
    public function notify($target, $content) {
    }
}
Example: Test Code
• Test Code
class AlertSystemTest extends PHPUnit_Framework_TestCase {
    public function test_sendNotify_FakeNStub_NoException() {
        $target_file = __DIR__ . '/data/targets.txt';

        $notifier = new StubNotifier();
        $provider = new FileNotifyTargetProvider($target_file);

        $alert_system = new AlertSystem(
            $notifier,
            $provider
        );
        $alert_system->send_notify('Alert!!');
    }
}
Manual Fake or Stub
• Pros
  – Fake or stub can be used as library
  – Shared implementation
• Cons
  – Different scenarios need different implementation
  – Testing class explosion
Manual Stub or Fake
• Cons
  – Need extra efforts/logics for behaviors
     • Setting return value
     • Setting thrown exception
  – Hard to validate
     • Calling sequence of functions
     • Passing arguments for functions
     • The method should be called
Test Doubles
• Using manual stub and mock
  – Is $notifier->notify() be called?
  – Does the target of $notifier->notify equal to
    expect target?
  – Does the content of $notifier->notify equal
    to expect target?
Mock objects
• Mock Objects
  – Mocks are objects pre-programmed with
    expectations, which form a specification of the
    calls they are expected to receive.
Mock Object Example
• Mock Object Example
 public function test_sendNotify_Mock_NoException() {

     $notify_content = 'fake_content';
     $mock_notifier = $this->getMock('NotifierInterface');
     $mock_notifier->expects($this->once())
                   ->method('notify')
                   ->with($this->anything(),
                          $this->equalTo($notify_content));

     $alert_system = new AlertSystem(
       $mock_notifier,
       $stub_provider
     );
     $alert_system->send_notify('Alert!!');
 }
Mock Object Example
• Mock Object Verification
  – $notifier->notify is called only once
  – $notifier->notify 1st parameter can be
    anything
  – $notifier->notify 2nd parameter should be
    equal to $notify_content
Using PHPUnit Stub
• Return Value
public function test_sendNotify_Mock_NoException() {

    $stub_provider = $this->getMock('NotifyTargetProviderInterface');
    $targets = array('hubert');
    $stub_provider->expects($this->any())
                  ->method('get_targets')
                  ->will($this->returnValue($targets));

    $alert_system = new AlertSystem(
      $mock_notifier,
      $stub_provider
    );
    $alert_system->send_notify('Alert!!');
}
Using PHPUnit Stub
• Return one of the arguments
public function testReturnArgumentStub() {
  // Create a stub for the SomeClass class.
  $stub = $this->getMock('SomeClass');

    // Configure the stub.
    $stub->expects($this->any())
         ->method('doSomething')
         ->will($this->returnArgument(0));

    // $stub->doSomething('foo') returns 'foo'
    $this->assertEquals('foo', $stub->doSomething('foo'));

    // $stub->doSomething('bar') returns 'bar'
    $this->assertEquals('bar', $stub->doSomething('bar'));
}
Using PHPUnit Stub
• Return a value from a callback
     – Useful for “out” parameter
public function testReturnCallbackStub() {
  // Create a stub for the SomeClass class.
  $stub = $this->getMock('SomeClass');

    // Configure the stub.
    $stub->expects($this->any())
         ->method('doSomething')
         ->will($this->returnCallback('str_rot13'));

    // $stub->doSomething($argument) returns str_rot13($argument)
    $this->assertEquals('fbzrguvat', $stub->doSomething('something'));
}
PHPUnit Stub
• Throw Exception
public function testThrowExceptionStub() {
  // Create a stub for the SomeClass class.
  $stub = $this->getMock('SomeClass');

    // Configure the stub.
    $stub->expects($this->any())
         ->method('doSomething')
         ->will($this->throwException(new Exception));

    // $stub->doSomething() throws Exception
    $stub->doSomething();
}
Misconception About Mocks
• Mocks are just Stubs
  – Mock is behavior verification
     • Is the function called?
     • Is the parameter passed correctly?
  – Stub is used for state verification
  – References
     • Mocks Aren’t Stubs
        – http://martinfowler.com/articles/mocksArentStubs.html
Is it HARD to use stub/mock?
• Untestable code
  – Make Your Own Dependencies
  – Heavy Duty Constructors
  – Depend on Concrete Classes
  – Use Statics
  – Using Singleton Everywhere
  – Look for Everything You Need
Dependency Injection
• Without dependency injection
  – Use “new” operator inside your class
  – Make mock object injection difficult
• Dependency Injection
  – Inject dependencies through injectors
  – Injection method
     • Constructor
     • Setter
     • Dependency Injection Framework
AlertSystem again
• AlertSystem (Hard to Test)
     – Concrete classes
     – Make Your Own Dependencies
 class AlertSystem {

     public function send_notify($content) {
       $target_provider = new FileNotifyTargetProvider('data.txt');
       $notifier = new EmailNotifier('user', 'pass', $port);

         $notify_targets = $target_provider->get_targets();
         foreach ($notify_targets as $target) {
           $notifier->notify($target, $content);
         }
     }
 }
AlertSystem constructor injection
• Constructor Injection
class AlertSystem {

     protected $_notifier;
     protected $_target_provider;

     function __construct (
         NotifierInterface $notifier,
         NotifyTargetProviderInterface $provider
     ) {
         $this->_notifier = $notifier;
         $this->_target_provider = $provider;
     }

     public function send_notify($content) {
         $notify_targets = $this->_target_provider->get_targets();
         foreach ($notify_targets as $target) {
             $this->_notifier->notify($target, $content);
         }
     }
}
Not only for testing
• Single Responsibility Principle
  – Should alert system holds notifier and data
    provider logic?
  – Ex. Should the class read registry directly?
• Dependency Inversion Principle
• Open Close Principle
The Law of Demeter
• Definition
  – Each unit should have only limited knowledge
    about other units: only units "closely" related to
    the current unit.
  – Each unit should only talk to its friends; don't talk
    to strangers.
  – Only talk to your immediate friends.
Violation of the Law
• How do you test for?
  – Mock for mock object, for another mock object
  – Like Looking for a Needle in the Haystack
  class Monitor {
    SparkPlug sparkPlug;
    Monitor(Context context) {
      this.sparkPlug = context.
        getCar().getEngine().
        getPiston().getSparkPlug();
    }
  }
Law of Demeter - Explicit
• Explicit
   – We should not need to know the details of
     collaborators
    class Mechanic {
      Engine engine;
      Mechanic(Engine engine) {
        this.engine = engine;
       }
    }
Guide – Write Testable Code
• Bad smell for non-testable Code
  – Constructor does real work
  – Digging into collaborators
  – Brittle Global State & Singletons
  – Class Does Too Much
• References
  – Guide – Write Testable Code
  – http://misko.hevery.com/attachments/Guide-
    Writing%20Testable%20Code.pdf
Conclusion
• Writing good unit tests is hard
• Good OO design brings good testability
• Using stub/mock from mocking framework
Q&A
PHPUnit Log File
• Junit Format
<testsuites>
  <testsuite name="AlertSystemTest"
file="/usr/home/hubert/own/work/trend/process/CI/php/tests/AlertSystemTe
st.php" tests="2" assertions="0" failures="1" errors="0"
time="0.031119">
    <testcase name="test_sendNotify_FakeNStub_NoException"
class="AlertSystemTest"
file="/usr/home/hubert/own/work/trend/process/CI/php/tests/AlertSystemTe
st.php" line="8" assertions="0" time="0.006881"/>
  </testsuite>
</testsuites>
PHPUnit Coverage
• PHPUnit Coverage
  – Need Xdebug
  – HTML format

Weitere ähnliche Inhalte

Was ist angesagt?

PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objectsLim Chanmann
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
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
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash CourseColin O'Dell
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingMark Rickerby
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringIngo Schommer
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
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
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in LaravelAhmed Yahia
 

Was ist angesagt? (20)

Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
 
Java best practices
Java best practicesJava best practices
Java best practices
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
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
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in Laravel
 

Andere mochten auch

Legal analysis of source code
Legal analysis of source codeLegal analysis of source code
Legal analysis of source codeRobert Viseur
 
Susan and Marco\'s Trip to Obama 2009 Inauguration
Susan and Marco\'s Trip to Obama 2009 InaugurationSusan and Marco\'s Trip to Obama 2009 Inauguration
Susan and Marco\'s Trip to Obama 2009 Inaugurationsusandkirby
 
Work History
Work HistoryWork History
Work HistoryConvinsys
 
USMEP Presentation
USMEP PresentationUSMEP Presentation
USMEP PresentationAl Hamman
 
Tiger shark powerpoint
Tiger shark   powerpointTiger shark   powerpoint
Tiger shark powerpointKelly Berry
 
IAサミットは誰のものか
IAサミットは誰のものかIAサミットは誰のものか
IAサミットは誰のものかNaoko Kawachi
 
Banking on Mobile!
Banking on Mobile!Banking on Mobile!
Banking on Mobile!Aman Narain
 
Theme 1 Eye of the Storm vocabulary
Theme 1 Eye of the Storm vocabularyTheme 1 Eye of the Storm vocabulary
Theme 1 Eye of the Storm vocabularyPEDH
 
La bamba vocabulary_pp jan 2013
La bamba vocabulary_pp jan 2013La bamba vocabulary_pp jan 2013
La bamba vocabulary_pp jan 2013PEDH
 
Theme 2 mae jemison vocabulary flash cards mod 2013 pholt
Theme 2   mae jemison vocabulary flash cards mod 2013 pholtTheme 2   mae jemison vocabulary flash cards mod 2013 pholt
Theme 2 mae jemison vocabulary flash cards mod 2013 pholtPEDH
 
Lesson 13 vocab
Lesson 13 vocabLesson 13 vocab
Lesson 13 vocabPEDH
 
T3dallas typoscript
T3dallas typoscriptT3dallas typoscript
T3dallas typoscriptzdavis
 
Proyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi kontenProyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi kontenWikimedia Indonesia
 
Geokit In Social Apps
Geokit In Social AppsGeokit In Social Apps
Geokit In Social AppsPaul Jensen
 
Balanced Scorecard system: Strategy Map
Balanced Scorecard system: Strategy MapBalanced Scorecard system: Strategy Map
Balanced Scorecard system: Strategy MapEvgenia_Parkina
 
Projducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooRProjducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooRAitor Padilla Mulero
 
Theme 1 Volcanoes Vocabulary Natures Fury
Theme 1 Volcanoes Vocabulary Natures FuryTheme 1 Volcanoes Vocabulary Natures Fury
Theme 1 Volcanoes Vocabulary Natures FuryPEDH
 
Capstone Project EDAM5039
Capstone Project EDAM5039Capstone Project EDAM5039
Capstone Project EDAM5039guest92ff42
 
Rules Of Brand Fiction from @BettyDraper and @Roger_Sterling
Rules Of Brand Fiction from @BettyDraper and @Roger_SterlingRules Of Brand Fiction from @BettyDraper and @Roger_Sterling
Rules Of Brand Fiction from @BettyDraper and @Roger_SterlingHelen Klein Ross
 

Andere mochten auch (20)

PHPUnit Cheat Sheet
PHPUnit Cheat SheetPHPUnit Cheat Sheet
PHPUnit Cheat Sheet
 
Legal analysis of source code
Legal analysis of source codeLegal analysis of source code
Legal analysis of source code
 
Susan and Marco\'s Trip to Obama 2009 Inauguration
Susan and Marco\'s Trip to Obama 2009 InaugurationSusan and Marco\'s Trip to Obama 2009 Inauguration
Susan and Marco\'s Trip to Obama 2009 Inauguration
 
Work History
Work HistoryWork History
Work History
 
USMEP Presentation
USMEP PresentationUSMEP Presentation
USMEP Presentation
 
Tiger shark powerpoint
Tiger shark   powerpointTiger shark   powerpoint
Tiger shark powerpoint
 
IAサミットは誰のものか
IAサミットは誰のものかIAサミットは誰のものか
IAサミットは誰のものか
 
Banking on Mobile!
Banking on Mobile!Banking on Mobile!
Banking on Mobile!
 
Theme 1 Eye of the Storm vocabulary
Theme 1 Eye of the Storm vocabularyTheme 1 Eye of the Storm vocabulary
Theme 1 Eye of the Storm vocabulary
 
La bamba vocabulary_pp jan 2013
La bamba vocabulary_pp jan 2013La bamba vocabulary_pp jan 2013
La bamba vocabulary_pp jan 2013
 
Theme 2 mae jemison vocabulary flash cards mod 2013 pholt
Theme 2   mae jemison vocabulary flash cards mod 2013 pholtTheme 2   mae jemison vocabulary flash cards mod 2013 pholt
Theme 2 mae jemison vocabulary flash cards mod 2013 pholt
 
Lesson 13 vocab
Lesson 13 vocabLesson 13 vocab
Lesson 13 vocab
 
T3dallas typoscript
T3dallas typoscriptT3dallas typoscript
T3dallas typoscript
 
Proyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi kontenProyek penciptaan dan digitalisasi konten
Proyek penciptaan dan digitalisasi konten
 
Geokit In Social Apps
Geokit In Social AppsGeokit In Social Apps
Geokit In Social Apps
 
Balanced Scorecard system: Strategy Map
Balanced Scorecard system: Strategy MapBalanced Scorecard system: Strategy Map
Balanced Scorecard system: Strategy Map
 
Projducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooRProjducció i consum d'energia AitoooR
Projducció i consum d'energia AitoooR
 
Theme 1 Volcanoes Vocabulary Natures Fury
Theme 1 Volcanoes Vocabulary Natures FuryTheme 1 Volcanoes Vocabulary Natures Fury
Theme 1 Volcanoes Vocabulary Natures Fury
 
Capstone Project EDAM5039
Capstone Project EDAM5039Capstone Project EDAM5039
Capstone Project EDAM5039
 
Rules Of Brand Fiction from @BettyDraper and @Roger_Sterling
Rules Of Brand Fiction from @BettyDraper and @Roger_SterlingRules Of Brand Fiction from @BettyDraper and @Roger_Sterling
Rules Of Brand Fiction from @BettyDraper and @Roger_Sterling
 

Ähnlich wie Test in action week 3

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
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentMark Niebergall
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
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
 
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
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
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
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitMichelangelo van Dam
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 

Ähnlich wie Test in action week 3 (20)

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
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
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
 
Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
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
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 

Kürzlich hochgeladen

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Kürzlich hochgeladen (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

Test in action week 3

  • 1. Test in Action – Week 3 Stub / Mock Hubert Chan
  • 2. Back to Basics • Wikipedia said unit testing is – A software verification and validation method in which a programmer tests if individual units of source code are fit for use.
  • 3. Dependency in the Test • System Under Test (SUT) Dependency – SUT need another module to perform its task • Handler need a $dbmodel to perform query • $handler = new Handler($dbmodel);
  • 4. Real Object is Hard to Test • Real object – Supplies non-deterministic results • (e.g. the current temperature) – Difficult to create or reproduce (e.g. network fail) – Slow (e.g. database) – Does not yet exist or may change behavior
  • 5. Substitute Dependency • Using Fake – Fake is anything not real • Fake techniques – Mock object – Stub object – Fake object
  • 6. Stub Objects • Stub Objects – Stubs provide canned answers to calls made during the test – Usually not responding at all to anything outside what's programmed in for the test
  • 7. Fake Objects • Fake Objects – Fake objects have working implementations – Usually take some shortcut, which makes them not suitable for production. – Example • An in-memory file system • An in-memory registry manager
  • 9. Example: AlertSystem • Component Overview – AlertSystem • Send notification to the targets, such as e-mail or SMS notifier. – NotifierInterface instance • Send actually notification to the target – NotifierTargetProviderInterface instance • Provide a target array to send notification
  • 10. AlertSystem Test • Dependency Analysis – Collaboration Classes • NotifierInterface • NotifierTargetProviderInterface • Tests should – Only focus on AlertSystem – Fake the dependency
  • 11. Make a Fake? • FileNotifyTargetProvider class FileNotifyTargetProvider implements NotifyTargetProviderInterface { function __construct($filename) { $this->_filename = $filename; } public function get_targets() { $targets = array(); $handle = @fopen($this->_filename, "r"); while (($target = fgets($handle)) !== FALSE) { $targets[] = $target; } return $targets; } }
  • 12. Make a Stub? • StubNotifier class StubNotifier implements NotifierInterface { public function notify($target, $content) { } }
  • 13. Example: Test Code • Test Code class AlertSystemTest extends PHPUnit_Framework_TestCase { public function test_sendNotify_FakeNStub_NoException() { $target_file = __DIR__ . '/data/targets.txt'; $notifier = new StubNotifier(); $provider = new FileNotifyTargetProvider($target_file); $alert_system = new AlertSystem( $notifier, $provider ); $alert_system->send_notify('Alert!!'); } }
  • 14. Manual Fake or Stub • Pros – Fake or stub can be used as library – Shared implementation • Cons – Different scenarios need different implementation – Testing class explosion
  • 15. Manual Stub or Fake • Cons – Need extra efforts/logics for behaviors • Setting return value • Setting thrown exception – Hard to validate • Calling sequence of functions • Passing arguments for functions • The method should be called
  • 16. Test Doubles • Using manual stub and mock – Is $notifier->notify() be called? – Does the target of $notifier->notify equal to expect target? – Does the content of $notifier->notify equal to expect target?
  • 17. Mock objects • Mock Objects – Mocks are objects pre-programmed with expectations, which form a specification of the calls they are expected to receive.
  • 18. Mock Object Example • Mock Object Example public function test_sendNotify_Mock_NoException() { $notify_content = 'fake_content'; $mock_notifier = $this->getMock('NotifierInterface'); $mock_notifier->expects($this->once()) ->method('notify') ->with($this->anything(), $this->equalTo($notify_content)); $alert_system = new AlertSystem( $mock_notifier, $stub_provider ); $alert_system->send_notify('Alert!!'); }
  • 19. Mock Object Example • Mock Object Verification – $notifier->notify is called only once – $notifier->notify 1st parameter can be anything – $notifier->notify 2nd parameter should be equal to $notify_content
  • 20. Using PHPUnit Stub • Return Value public function test_sendNotify_Mock_NoException() { $stub_provider = $this->getMock('NotifyTargetProviderInterface'); $targets = array('hubert'); $stub_provider->expects($this->any()) ->method('get_targets') ->will($this->returnValue($targets)); $alert_system = new AlertSystem( $mock_notifier, $stub_provider ); $alert_system->send_notify('Alert!!'); }
  • 21. Using PHPUnit Stub • Return one of the arguments public function testReturnArgumentStub() { // Create a stub for the SomeClass class. $stub = $this->getMock('SomeClass'); // Configure the stub. $stub->expects($this->any()) ->method('doSomething') ->will($this->returnArgument(0)); // $stub->doSomething('foo') returns 'foo' $this->assertEquals('foo', $stub->doSomething('foo')); // $stub->doSomething('bar') returns 'bar' $this->assertEquals('bar', $stub->doSomething('bar')); }
  • 22. Using PHPUnit Stub • Return a value from a callback – Useful for “out” parameter public function testReturnCallbackStub() { // Create a stub for the SomeClass class. $stub = $this->getMock('SomeClass'); // Configure the stub. $stub->expects($this->any()) ->method('doSomething') ->will($this->returnCallback('str_rot13')); // $stub->doSomething($argument) returns str_rot13($argument) $this->assertEquals('fbzrguvat', $stub->doSomething('something')); }
  • 23. PHPUnit Stub • Throw Exception public function testThrowExceptionStub() { // Create a stub for the SomeClass class. $stub = $this->getMock('SomeClass'); // Configure the stub. $stub->expects($this->any()) ->method('doSomething') ->will($this->throwException(new Exception)); // $stub->doSomething() throws Exception $stub->doSomething(); }
  • 24. Misconception About Mocks • Mocks are just Stubs – Mock is behavior verification • Is the function called? • Is the parameter passed correctly? – Stub is used for state verification – References • Mocks Aren’t Stubs – http://martinfowler.com/articles/mocksArentStubs.html
  • 25. Is it HARD to use stub/mock? • Untestable code – Make Your Own Dependencies – Heavy Duty Constructors – Depend on Concrete Classes – Use Statics – Using Singleton Everywhere – Look for Everything You Need
  • 26. Dependency Injection • Without dependency injection – Use “new” operator inside your class – Make mock object injection difficult • Dependency Injection – Inject dependencies through injectors – Injection method • Constructor • Setter • Dependency Injection Framework
  • 27. AlertSystem again • AlertSystem (Hard to Test) – Concrete classes – Make Your Own Dependencies class AlertSystem { public function send_notify($content) { $target_provider = new FileNotifyTargetProvider('data.txt'); $notifier = new EmailNotifier('user', 'pass', $port); $notify_targets = $target_provider->get_targets(); foreach ($notify_targets as $target) { $notifier->notify($target, $content); } } }
  • 28. AlertSystem constructor injection • Constructor Injection class AlertSystem { protected $_notifier; protected $_target_provider; function __construct ( NotifierInterface $notifier, NotifyTargetProviderInterface $provider ) { $this->_notifier = $notifier; $this->_target_provider = $provider; } public function send_notify($content) { $notify_targets = $this->_target_provider->get_targets(); foreach ($notify_targets as $target) { $this->_notifier->notify($target, $content); } } }
  • 29. Not only for testing • Single Responsibility Principle – Should alert system holds notifier and data provider logic? – Ex. Should the class read registry directly? • Dependency Inversion Principle • Open Close Principle
  • 30. The Law of Demeter • Definition – Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. – Each unit should only talk to its friends; don't talk to strangers. – Only talk to your immediate friends.
  • 31. Violation of the Law • How do you test for? – Mock for mock object, for another mock object – Like Looking for a Needle in the Haystack class Monitor { SparkPlug sparkPlug; Monitor(Context context) { this.sparkPlug = context. getCar().getEngine(). getPiston().getSparkPlug(); } }
  • 32. Law of Demeter - Explicit • Explicit – We should not need to know the details of collaborators class Mechanic { Engine engine; Mechanic(Engine engine) { this.engine = engine; } }
  • 33. Guide – Write Testable Code • Bad smell for non-testable Code – Constructor does real work – Digging into collaborators – Brittle Global State & Singletons – Class Does Too Much • References – Guide – Write Testable Code – http://misko.hevery.com/attachments/Guide- Writing%20Testable%20Code.pdf
  • 34. Conclusion • Writing good unit tests is hard • Good OO design brings good testability • Using stub/mock from mocking framework
  • 35. Q&A
  • 36. PHPUnit Log File • Junit Format <testsuites> <testsuite name="AlertSystemTest" file="/usr/home/hubert/own/work/trend/process/CI/php/tests/AlertSystemTe st.php" tests="2" assertions="0" failures="1" errors="0" time="0.031119"> <testcase name="test_sendNotify_FakeNStub_NoException" class="AlertSystemTest" file="/usr/home/hubert/own/work/trend/process/CI/php/tests/AlertSystemTe st.php" line="8" assertions="0" time="0.006881"/> </testsuite> </testsuites>
  • 37. PHPUnit Coverage • PHPUnit Coverage – Need Xdebug – HTML format

Hinweis der Redaktion

  1. http://misko.hevery.com/2008/07/24/how-to-write-3v1l-untestable-code/
  2. http://tutorials.jenkov.com/dependency-injection/index.html
  3. https://secure.wikimedia.org/wikipedia/en/wiki/Law_of_Demeter