SlideShare a Scribd company logo
Test in Action – Week 4
       Good Tests
      Hubert Chan
Test Lint
• Test Lint
  – Trustworthiness
  – Maintainability
  – Readability
• References
  – Test Lint (http://docs.typemock.com/lint/ )
Trustworthy Tests
• Trustworthy Tests
  – Always Asserts Something
  – Avoid unpredictable factor
  – Don’t depend on other tests
  – Avoid Logic in Tests
Always Asserts Something
• Always Asserts Something
  – Assertion means “Verification”
  – Unit Tests need to “Check Something”
• Exceptions
  – Check exception not thrown
     • Name “Login_Call_NoExceptionThrown”
  – Specified Mock Object
Avoid Unpredictable Factor
• Avoid Unpredictable Factor
  – Unpredictable Factor
     • Random Number
     • Date Time
  – Cause
     • Unreliable/Inconsistent Result
     • Hard to write Assertion statement
Avoid Unpredictable Factor
• Solution
  – Use Fake
  – Use hard-code values
  $random = rand();
  $this->assertEquals(1, sut.DoSomething($random));




  $pseudoRandom = 1234;
  $this->assertEquals(1, sut.DoSomething(pseudoRandom));
Don’t Depend on Other Tests
• Example
 class LogAnalyzerDependTest extends PHPUnit_Framework_TestCase {

     public function test_LogAnalyzerDepend_Construct_NoException() {
       $this->analyzer = new LogAnalyzerDepend();
       $this->analyzer->initialize();
     }

     public function test_IsValid_InValidContent_ReturnFalse() {
       $this->test_LogAnalyzerDepend_Construct_NoException();
       $this->assertFalse($this->analyzer->is_valid('abc'));
     }
 }
Don’t Depend on Other Tests
• Symptom
  – A test calls another tests
  – It requires other tests to create/delete objects
  – A test depends on system state set by other tests
  – Test order matters
Don’t Depend on Other Tests
• Why not?
  – Cannot provide explicit testing result
  – Implicit tests flow
  – The testA failed because callee testB failed
• Solution
  – Extract reused code to utility
  – For create/delete object, use “setUp” and
    “tearDown” instead
Avoid Logic in Tests
• Test more than one thing
  – Number of Assertion > 1
  – Logics better not in tests
     • switch, if, or else statement
     • foreach, for, or while loops
Avoid Logic in Tests- Example
• Test Code
 public function test_ImplodeAndExplode_ValidContent_CorrectResult() {
   $instance = new MoreThanOne();
   $test_array = array('1', '2', '3');
   $test_string = '1,2,3';

     for ($i = 0; $i < 2; $i++) {
       if ($i === 0) { // Test explode2
         $result = $instance->explode2(',', $test_string);
         $this->assertEquals($test_array, $result);
       }
       elseif ($i === 1) { // Test implode2
         $result = $instance->implode2(',', $test_array);
         $this->assertEquals($test_string, $result);
       }
     }
 }
Make Clean Tests
• Change your tests
  – Removing invalid tests
  – Renaming / Refactoring tests
  – Eliminating duplicate tests
Trustworthiness – Do it
• Do it
  – Testing only one thing
  – Keep safe green zone
     • No dependency to real database/network
     • Keep result consistent
  – Assuring code coverage
  – Attitude
     • Add a unit test for newly tickets/trackers
Maintainable Tests
• Maintainable Tests
  – Test public function only
  – Don’t Repeat Yourself
     • Use Factory Function over Multiple Object Creation
     • Use setUp
  – Using setUp in a maintainable manner
  – Avoid Over Specification in Tests
  – Avoid multiple asserts
Test Public Function Only
• Test Public Function Only
  – Design/Program by Contract
     • Private/Protected method might be changed
  – Extract private/protected function to new class
     • Adopt Single Responsibility Principle (SRP)
Semantic Change
• Semantic Change is really a PAIN
  – API change may break all tests
  – Each test need to be changed
 public function test_IsValid_InValidContent_ReturnFalse_New() {
   $analyzer = new LogAnalyzer();
   $analyzer->initialize(); // new requirement
   $this->assertFalse($analyzer->is_valid('abc'));
 }
Use Factory Function over Multiple
           Object Creation
• Use a factory function
 protected function create_LogAnalyzer() { // Factory Method
   $analyzer = new LogAnalyzer();
   $analyzer->initialize(); // New API handled here
   return $analyzer;
 }
 public function test_IsValid_InValidContent_ReturnFalse() {
   $analyzer = $this->create_LogAnalyzer(); // Use factory
   $this->assertFalse($analyzer->is_valid('abc'));
 }
Use setUp over Multiple Object
                Creation
• Use setUp
 protected function setUp() { // setUp method
   $this->analyzer = new LogAnalyzer();
   $this->analyzer->initialize(); // New API handled here
 }

 public function test_IsValid_InValidContent_ReturnFalse() {
   $this->assertFalse($this->analyzer->is_valid('abc'));
 }
 public function test_IsValid_ValidContent_ReturnFalse() {
   $this->assertTrue($this->analyzer->is_valid('valid'));
 }
Maintainable setUp
• Maintainable setUp
  – setUp() should be generic
     • Cohesion
     • Initialized object should be used in all tests
     • Might not be appropriate to arrange mock/stub in
       setUp()
  – setUp() should be kept his readability
Avoid Over Specification in Test
• Over specified in test
  – Verify internal state/behavior of object
  – Using mocks when stubs are enough
  – A test assumes specific order or exact string
    matches when it isn’t required.
Verify internal state/behavior of object
• Solution
  – Never verify internal state/behavior
  – Maybe no need to test
  public function
  test_Initialize_WhenCalled_SetsDefaultDelimiterIsTabDelimiter(){
    $analyzer = new LogAnalyzer();
    $this->assertEquals(null,
      $analyzer->GetInternalDefaultDelimiter()
    );

      $analyzer->Initialize();
      $this->assertEquals('t',
        $analyzer->GetInternalDefaultDelimiter()
      );
  }
Avoid Multiple Asserts
• Why not?
  – Assertion failure will throw exception. Multiple
    assertion cannot get all failure point at once
  – Test multiple thing in one tests
• Solution
  – Separate tests for different assertion
  – Use data provider / parameter tests
Data Provider Sample
• Test Code
class DataTest extends PHPUnit_Framework_TestCase {
  /**
  * @dataProvider provider
  */
  public function testAdd($a, $b, $c) {
    $this->assertEquals($c, $a + $b);
  }
    public function   provider() {
      return array(
        array(0, 0,   0),
        array(0, 1,   1),
        array(1, 0,   1),
        array(1, 1,   3)
      );
    }
}
Readable Tests
•   Test Naming
•   Variable Naming
•   Good Assert Message
•   Separate Arrange and Assertion
•   Mock and Stub Naming
Test Naming
• Function Name
  – Test function name should be
    test_<function>_<scenario>_<expect_behavior>
  – Example
    • test_escape_evenBackSlashesData_successEscape
Variable Name
• Avoid Hard Code in tests
 public function test BadlyNamedTest() {
   $log = new LogAnalyzer();
   $result= log.GetLineCount("abc.txt");
   $this->assertEquals(-100, result);
 }


 public function test WellNamedTest() {
   $log = new LogAnalyzer();
   $COULD_NOT_READ_FILE = -100;
   $result= log.GetLineCount("abc.txt");
   $this->assertEquals($COULD_NOT_READ_FILE, result);
 }
Good Assertion Message
• Good Assertion Message
  – Don’t repeat what the built-in test framework
    outputs to the console.
  – Don’t repeat what the test name explains.
  – If you don’t have anything good to say, don’t say
    anything.
  – Write what should have happened or what failed
Separate Arrange and Assertion
• Separate Arrange and Assertion
 public function test_BadAssertMessage() {
   $this->assertEquals(COULD_NOT_READ_FILE,
                       log->GetLineCount("abc.txt")
   );
 }



 public function test_GoodAssertMessage() {
   $result = log->GetLineCount("abc.txt");
   $this->assertEquals($COULD_NOT_READ_FILE, $result);
 }
Mock and Stub Naming
• Include “mock” and “stub” in variable name
 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!!');
 }
Q&A
PHPUnit and Selenium
• Use PHPUnit to do
  – Integration Test
  – Acceptance Test
• References
  – PHPUnit Selenium
     • http://www.phpunit.de/manual/current/en/selenium.h
       tml
     • http://seleniumhq.org/documentation/
PHPUnit and Selenium
• Use PHPUnit and Selenium
class WebTest extends PHPUnit_Extensions_SeleniumTestCase {
  protected function setUp() {
    $this->setBrowser('*firefox');
    $this->setBrowserUrl('http://www.example.com/');
  }

    public function testTitle() {
      $this->open('http://www.example.com/');
      $this->assertTitle('Example WWW Page');
    }
}
PHPUnit and Selenium

More Related Content

What's hot

Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
Ingo Schommer
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
Mike Lively
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
Mark Rickerby
 
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
 
Java best practices
Java best practicesJava best practices
Java best practices
Ray Toal
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
Ingo Schommer
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Yi-Huan Chan
 
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
Paweł Michalik
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
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
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
GeeksLab Odessa
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
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
SWIFTotter Solutions
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in Laravel
Ahmed Yahia
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
Colin O'Dell
 
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
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
Hector Canto
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
Mindfire Solutions
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
Jeremy Cook
 

What's hot (20)

Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
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
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
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
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
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
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
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
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
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
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in Laravel
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 

Viewers also liked

Tech Blogs - Pakistani Prospective
Tech Blogs -  Pakistani ProspectiveTech Blogs -  Pakistani Prospective
Tech Blogs - Pakistani Prospective
Farhan Chawla
 
Presentancion halloween 2011
Presentancion halloween 2011Presentancion halloween 2011
Presentancion halloween 2011pallaresdiaz
 
Visual Thinking for Islamic Education
Visual Thinking for Islamic EducationVisual Thinking for Islamic Education
Visual Thinking for Islamic Education
Syukran
 
Q1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De NemoursQ1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De Nemoursguestc4fcf72
 
Shari Gunn
Shari GunnShari Gunn
Shari Gunn
tieadmin
 
A Christmas Story
A Christmas StoryA Christmas Story
A Christmas Story
BibliotecaRoque
 
IAサミットは誰のものか
IAサミットは誰のものかIAサミットは誰のものか
IAサミットは誰のものか
Naoko Kawachi
 
April 23, 2015 Joint Elected Boards meeting
April 23, 2015 Joint Elected Boards meetingApril 23, 2015 Joint Elected Boards meeting
April 23, 2015 Joint Elected Boards meeting
Chatham Economic Development Corporation
 
What can Michelangelo teach us about innovation?
What can Michelangelo teach us about innovation?What can Michelangelo teach us about innovation?
What can Michelangelo teach us about innovation?Aman Narain
 
Design for asatizah Slides
Design for asatizah SlidesDesign for asatizah Slides
Design for asatizah Slides
Syukran
 
Viva La Revolution: Why Universal Banking is under siege and what needs to be...
Viva La Revolution: Why Universal Banking is under siege and what needs to be...Viva La Revolution: Why Universal Banking is under siege and what needs to be...
Viva La Revolution: Why Universal Banking is under siege and what needs to be...
Aman Narain
 
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...
Wikimedia Indonesia
 
Pijar teologi materi komunikasi-final
Pijar teologi   materi komunikasi-finalPijar teologi   materi komunikasi-final
Pijar teologi materi komunikasi-final
Wikimedia Indonesia
 
Who Is Muhammad (Pbuh)
Who Is Muhammad (Pbuh)Who Is Muhammad (Pbuh)
Who Is Muhammad (Pbuh)
Syukran
 
Hannah Montana
Hannah MontanaHannah Montana
Hannah Montanaamoto
 
Aspen Lion
Aspen LionAspen Lion
Aspen Lion
Kelly Berry
 
Taal Is Het Woord Niet
Taal Is Het Woord NietTaal Is Het Woord Niet
Taal Is Het Woord NietSoert
 
Perpustakaan digital Bebaskan Pengetahuan
Perpustakaan digital Bebaskan PengetahuanPerpustakaan digital Bebaskan Pengetahuan
Perpustakaan digital Bebaskan Pengetahuan
Wikimedia Indonesia
 

Viewers also liked (20)

Segundo Caraujulca Galvez
Segundo Caraujulca GalvezSegundo Caraujulca Galvez
Segundo Caraujulca Galvez
 
Tech Blogs - Pakistani Prospective
Tech Blogs -  Pakistani ProspectiveTech Blogs -  Pakistani Prospective
Tech Blogs - Pakistani Prospective
 
Presentancion halloween 2011
Presentancion halloween 2011Presentancion halloween 2011
Presentancion halloween 2011
 
Visual Thinking for Islamic Education
Visual Thinking for Islamic EducationVisual Thinking for Islamic Education
Visual Thinking for Islamic Education
 
Q1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De NemoursQ1 2009 Earning Report of Du Pont E I De Nemours
Q1 2009 Earning Report of Du Pont E I De Nemours
 
Shari Gunn
Shari GunnShari Gunn
Shari Gunn
 
A Christmas Story
A Christmas StoryA Christmas Story
A Christmas Story
 
A Christmas Story2
A Christmas Story2A Christmas Story2
A Christmas Story2
 
IAサミットは誰のものか
IAサミットは誰のものかIAサミットは誰のものか
IAサミットは誰のものか
 
April 23, 2015 Joint Elected Boards meeting
April 23, 2015 Joint Elected Boards meetingApril 23, 2015 Joint Elected Boards meeting
April 23, 2015 Joint Elected Boards meeting
 
What can Michelangelo teach us about innovation?
What can Michelangelo teach us about innovation?What can Michelangelo teach us about innovation?
What can Michelangelo teach us about innovation?
 
Design for asatizah Slides
Design for asatizah SlidesDesign for asatizah Slides
Design for asatizah Slides
 
Viva La Revolution: Why Universal Banking is under siege and what needs to be...
Viva La Revolution: Why Universal Banking is under siege and what needs to be...Viva La Revolution: Why Universal Banking is under siege and what needs to be...
Viva La Revolution: Why Universal Banking is under siege and what needs to be...
 
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...
 
Pijar teologi materi komunikasi-final
Pijar teologi   materi komunikasi-finalPijar teologi   materi komunikasi-final
Pijar teologi materi komunikasi-final
 
Who Is Muhammad (Pbuh)
Who Is Muhammad (Pbuh)Who Is Muhammad (Pbuh)
Who Is Muhammad (Pbuh)
 
Hannah Montana
Hannah MontanaHannah Montana
Hannah Montana
 
Aspen Lion
Aspen LionAspen Lion
Aspen Lion
 
Taal Is Het Woord Niet
Taal Is Het Woord NietTaal Is Het Woord Niet
Taal Is Het Woord Niet
 
Perpustakaan digital Bebaskan Pengetahuan
Perpustakaan digital Bebaskan PengetahuanPerpustakaan digital Bebaskan Pengetahuan
Perpustakaan digital Bebaskan Pengetahuan
 

Similar to Test in action week 4

Php tests tips
Php tests tipsPhp tests tips
Php tests tips
Damian Sromek
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
Thanh Robi
 
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
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
Michelangelo van Dam
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
markstory
 
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
 
Clean tests good tests
Clean tests   good testsClean tests   good tests
Clean tests good tests
Shopsys Framework
 
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
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
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
 
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
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
Mark Niebergall
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
Mark Baker
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
TestNG
TestNGTestNG
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
Hans Jones
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
Mike Lively
 

Similar to Test in action week 4 (20)

Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
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)
 
Clean tests good tests
Clean tests   good testsClean tests   good tests
Clean tests good tests
 
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
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
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
 
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
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
TestNG
TestNGTestNG
TestNG
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 

Recently uploaded

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
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
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
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
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
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
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
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

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
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
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
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
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...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
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...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Test in action week 4

  • 1. Test in Action – Week 4 Good Tests Hubert Chan
  • 2. Test Lint • Test Lint – Trustworthiness – Maintainability – Readability • References – Test Lint (http://docs.typemock.com/lint/ )
  • 3. Trustworthy Tests • Trustworthy Tests – Always Asserts Something – Avoid unpredictable factor – Don’t depend on other tests – Avoid Logic in Tests
  • 4. Always Asserts Something • Always Asserts Something – Assertion means “Verification” – Unit Tests need to “Check Something” • Exceptions – Check exception not thrown • Name “Login_Call_NoExceptionThrown” – Specified Mock Object
  • 5. Avoid Unpredictable Factor • Avoid Unpredictable Factor – Unpredictable Factor • Random Number • Date Time – Cause • Unreliable/Inconsistent Result • Hard to write Assertion statement
  • 6. Avoid Unpredictable Factor • Solution – Use Fake – Use hard-code values $random = rand(); $this->assertEquals(1, sut.DoSomething($random)); $pseudoRandom = 1234; $this->assertEquals(1, sut.DoSomething(pseudoRandom));
  • 7. Don’t Depend on Other Tests • Example class LogAnalyzerDependTest extends PHPUnit_Framework_TestCase { public function test_LogAnalyzerDepend_Construct_NoException() { $this->analyzer = new LogAnalyzerDepend(); $this->analyzer->initialize(); } public function test_IsValid_InValidContent_ReturnFalse() { $this->test_LogAnalyzerDepend_Construct_NoException(); $this->assertFalse($this->analyzer->is_valid('abc')); } }
  • 8. Don’t Depend on Other Tests • Symptom – A test calls another tests – It requires other tests to create/delete objects – A test depends on system state set by other tests – Test order matters
  • 9. Don’t Depend on Other Tests • Why not? – Cannot provide explicit testing result – Implicit tests flow – The testA failed because callee testB failed • Solution – Extract reused code to utility – For create/delete object, use “setUp” and “tearDown” instead
  • 10. Avoid Logic in Tests • Test more than one thing – Number of Assertion > 1 – Logics better not in tests • switch, if, or else statement • foreach, for, or while loops
  • 11. Avoid Logic in Tests- Example • Test Code public function test_ImplodeAndExplode_ValidContent_CorrectResult() { $instance = new MoreThanOne(); $test_array = array('1', '2', '3'); $test_string = '1,2,3'; for ($i = 0; $i < 2; $i++) { if ($i === 0) { // Test explode2 $result = $instance->explode2(',', $test_string); $this->assertEquals($test_array, $result); } elseif ($i === 1) { // Test implode2 $result = $instance->implode2(',', $test_array); $this->assertEquals($test_string, $result); } } }
  • 12. Make Clean Tests • Change your tests – Removing invalid tests – Renaming / Refactoring tests – Eliminating duplicate tests
  • 13. Trustworthiness – Do it • Do it – Testing only one thing – Keep safe green zone • No dependency to real database/network • Keep result consistent – Assuring code coverage – Attitude • Add a unit test for newly tickets/trackers
  • 14. Maintainable Tests • Maintainable Tests – Test public function only – Don’t Repeat Yourself • Use Factory Function over Multiple Object Creation • Use setUp – Using setUp in a maintainable manner – Avoid Over Specification in Tests – Avoid multiple asserts
  • 15. Test Public Function Only • Test Public Function Only – Design/Program by Contract • Private/Protected method might be changed – Extract private/protected function to new class • Adopt Single Responsibility Principle (SRP)
  • 16. Semantic Change • Semantic Change is really a PAIN – API change may break all tests – Each test need to be changed public function test_IsValid_InValidContent_ReturnFalse_New() { $analyzer = new LogAnalyzer(); $analyzer->initialize(); // new requirement $this->assertFalse($analyzer->is_valid('abc')); }
  • 17. Use Factory Function over Multiple Object Creation • Use a factory function protected function create_LogAnalyzer() { // Factory Method $analyzer = new LogAnalyzer(); $analyzer->initialize(); // New API handled here return $analyzer; } public function test_IsValid_InValidContent_ReturnFalse() { $analyzer = $this->create_LogAnalyzer(); // Use factory $this->assertFalse($analyzer->is_valid('abc')); }
  • 18. Use setUp over Multiple Object Creation • Use setUp protected function setUp() { // setUp method $this->analyzer = new LogAnalyzer(); $this->analyzer->initialize(); // New API handled here } public function test_IsValid_InValidContent_ReturnFalse() { $this->assertFalse($this->analyzer->is_valid('abc')); } public function test_IsValid_ValidContent_ReturnFalse() { $this->assertTrue($this->analyzer->is_valid('valid')); }
  • 19. Maintainable setUp • Maintainable setUp – setUp() should be generic • Cohesion • Initialized object should be used in all tests • Might not be appropriate to arrange mock/stub in setUp() – setUp() should be kept his readability
  • 20. Avoid Over Specification in Test • Over specified in test – Verify internal state/behavior of object – Using mocks when stubs are enough – A test assumes specific order or exact string matches when it isn’t required.
  • 21. Verify internal state/behavior of object • Solution – Never verify internal state/behavior – Maybe no need to test public function test_Initialize_WhenCalled_SetsDefaultDelimiterIsTabDelimiter(){ $analyzer = new LogAnalyzer(); $this->assertEquals(null, $analyzer->GetInternalDefaultDelimiter() ); $analyzer->Initialize(); $this->assertEquals('t', $analyzer->GetInternalDefaultDelimiter() ); }
  • 22. Avoid Multiple Asserts • Why not? – Assertion failure will throw exception. Multiple assertion cannot get all failure point at once – Test multiple thing in one tests • Solution – Separate tests for different assertion – Use data provider / parameter tests
  • 23. Data Provider Sample • Test Code class DataTest extends PHPUnit_Framework_TestCase { /** * @dataProvider provider */ public function testAdd($a, $b, $c) { $this->assertEquals($c, $a + $b); } public function provider() { return array( array(0, 0, 0), array(0, 1, 1), array(1, 0, 1), array(1, 1, 3) ); } }
  • 24. Readable Tests • Test Naming • Variable Naming • Good Assert Message • Separate Arrange and Assertion • Mock and Stub Naming
  • 25. Test Naming • Function Name – Test function name should be test_<function>_<scenario>_<expect_behavior> – Example • test_escape_evenBackSlashesData_successEscape
  • 26. Variable Name • Avoid Hard Code in tests public function test BadlyNamedTest() { $log = new LogAnalyzer(); $result= log.GetLineCount("abc.txt"); $this->assertEquals(-100, result); } public function test WellNamedTest() { $log = new LogAnalyzer(); $COULD_NOT_READ_FILE = -100; $result= log.GetLineCount("abc.txt"); $this->assertEquals($COULD_NOT_READ_FILE, result); }
  • 27. Good Assertion Message • Good Assertion Message – Don’t repeat what the built-in test framework outputs to the console. – Don’t repeat what the test name explains. – If you don’t have anything good to say, don’t say anything. – Write what should have happened or what failed
  • 28. Separate Arrange and Assertion • Separate Arrange and Assertion public function test_BadAssertMessage() { $this->assertEquals(COULD_NOT_READ_FILE, log->GetLineCount("abc.txt") ); } public function test_GoodAssertMessage() { $result = log->GetLineCount("abc.txt"); $this->assertEquals($COULD_NOT_READ_FILE, $result); }
  • 29. Mock and Stub Naming • Include “mock” and “stub” in variable name 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!!'); }
  • 30. Q&A
  • 31. PHPUnit and Selenium • Use PHPUnit to do – Integration Test – Acceptance Test • References – PHPUnit Selenium • http://www.phpunit.de/manual/current/en/selenium.h tml • http://seleniumhq.org/documentation/
  • 32. PHPUnit and Selenium • Use PHPUnit and Selenium class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this->setBrowser('*firefox'); $this->setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this->open('http://www.example.com/'); $this->assertTitle('Example WWW Page'); } }