SlideShare a Scribd company logo
1 of 20
Download to read offline
UNITTESTING IN SILVERSTRIPE
A couple of tricks you might not know about
Ingo Schommer (@chillu), October 2010
Wednesday, 17 November 2010
MORE EXPRESSIVE ASSERTIONS
Bad: Generic assertion, little debugging value
<?php
class MyFileCreatorTest extends FunctionalTest {
function testFileGeneration() {
$obj = new MyFileCreator();
$filepath = $obj->createFile();
$this->assertEquals(file_exists($filepath), true);
}
}
1) MyFileCreatorTest::testFileGeneration
Failed asserting that <boolean:true> matches expected
<boolean:false>.
Wednesday, 17 November 2010
MORE EXPRESSIVE ASSERTIONS
Good: Use assertions that communicate failures better
<?php
class MyFileCreatorTest extends FunctionalTest {
function testFileGeneration() {
$obj = new MyFileCreator();
$filepath = $obj->createFile();
$this->assertFileExists($filepath);
}
}
1) MyFileCreatorTest::testFileGeneration
Failed asserting that file "/my/path/file.txt" exists.
Wednesday, 17 November 2010
MORE EXPRESSIVE ASSERTIONS
Useful built-in assertions:
assertType(<string>, <object>)
assertArrayHasKey(<key>, <array>)
assertContains(<needle>, <haystack>)
assertEmailSent($to, $from = null, $subject = null, $content = null)
assertDOSContains($matches, $dataObjectSet)
Useful custom assertions in SapphireTest:
Wednesday, 17 November 2010
MORE EXPRESSIVE ASSERTIONS
$members = DataObject::get('Member');
$this->assertContains('test@test.com',$members->column('Email'));
$member = DataObject::get_one('Member', '"Email" = 'test@test.com'');
$this->assertType('Member', $member);
Using assertType()
Using DataObjectSet->column()
Wednesday, 17 November 2010
PHPUNIT EXECUTABLE INSTEAD OF SAKE
New feature since 2.4.3, backported to 2.3.9 as well
More features than proxying through “sake” CLI tool
Code coverage generation in “XML Clover” format
(which can be parsed by phpUnderControl and other tools)
Wednesday, 17 November 2010
PHPUNIT EXECUTABLE INSTEAD OF SAKE
With “sake”
phpunit .
phpunit sapphire
phpunit sapphire/tests/DataObjectTest.php
phpunit --coverage-html assets/
sake dev/tests/all
sake dev/tests/modules/sapphire
sake dev/tests/DataObjectTest
sake dev/tests/coverage
With “phpunit”
Wednesday, 17 November 2010
PHPUNIT: RUN ALLTESTS IN A FOLDER
phpunit --verbose sapphire/tests/security
PHPUnit 3.5.3 by Sebastian Bergmann.
sapphire/tests/security
BasicAuthTest
....
GroupTest
...
Time: 9 seconds, Memory: 83.50Mb
OK (72 tests, 286 assertions)
More granular control over which tests are run
Filepath autocompletion built-in on CLI
Wednesday, 17 November 2010
PHPUNIT: RUN ONLY ONETEST METHOD
Less hacky than commenting out other tests
Supports regular expressions
phpunit --filter testDelete sapphire/tests/DataObjectTest.php
PHPUnit 3.5.3 by Sebastian Bergmann.
.
Time: 1 second, Memory: 64.75Mb
Wednesday, 17 November 2010
FASTERTESTSTHROUGH SQLITE3
Up to 10x faster test execution¹ means
“Test Driven Development” (TDD) is fun again!Thanks Andreas :)
phpunit mysite/tests '' db=sqlite3
...
Time: 2:44 seconds, Memory: 113.75Mb
phpunit mysite/tests
...
Time: 22:56, Memory: 116.75Mb
PostgreSQL Sqlite3
¹ Internal project on SilverStripe 2.4.2, with 97 tests and 410 assertions.
Postgresql and SQLite3 modules both on trunk.
Wednesday, 17 November 2010
FASTERTESTSTHROUGH SQLITE3
Needs the sqlite3 module in your project
http://silverstripe.org/sqlite-database/
Simple modification in mysite/_config.php
require_once('conf/ConfigureFromEnv.php');
// ...
if(Director::isDev() && @$_REQUEST['db'] == 'sqlite3') {
$databaseConfig['type'] = 'SQLite3Database';
}
Not a complete replacement to running tests on the
actual database driver, but most of the time implementations are the same.
Wednesday, 17 November 2010
DEBUGGING A FIXTURE
YAML fixtures are more concise than SQL inserts
Problem: You have to run queries and joins in your head
Wednesday, 17 November 2010
DEBUGGING A FIXTURE
For more complex data models, looking at SQL can be easier
SilverStripe lets you load aYAML fixture into a temporary database
through http://localhost/dev/tests/startsession
Wednesday, 17 November 2010
SEPARATE INTEGRATION AND UNITTESTS
A UnitTest (SapphireTest class) covers an isolated aspect of a class,
e.g. one method call.
An IntegrationTest (FunctionalTest class) tests the sum of its parts,
in SilverStripe mostly HTTP requests and their HTML responses.
Wednesday, 17 November 2010
SEPARATE INTEGRATION AND UNITTESTS
Unit and IntegrationTests complement each other,
both are necessary and have different intentions.
Good practice: Separate tests into different folders.
Example: mysite/tests/unit and mysite/tests/integration
Idea: Run coverage reports separately for unit and integration tests
Wednesday, 17 November 2010
WRITE QUALITYTESTS
Lack of test coverage points to problems,
but high coverage doesn’t automatically mean quality code
class HomepageTest extends FunctionalTest {
function testResponse() {
$response = $this->get('home');
$this->assertNotNull($response->getBody());
$this->assertEquals($response->getStatusCode(200));
}
}
Probably gives you 80% code coverage for a Homepage class,
but failures don’t tell you anything useful.
Bad example:
Wednesday, 17 November 2010
WRITE QUALITYTESTS
High code coverage is the side effect of writing quality tests,
not a goal in itself.
Recommendation:
Strive for high unit test coverage,
and highlevel “smoke tests” through integration tests
Wednesday, 17 November 2010
WRITE FLEXIBLE INTEGRATIONTESTS
<div class="sidebar">
<ul>
<li class="news-item">
<a href="mylink">My first news</a>
</li>
<!-- ... -->
</ul>
</div>
class HomepageTest extends FunctionalTest {
function testSidebarShowsLatestNews() {
$response = $this->get('home');
$newsEls = $response->cssParser()->getBySelector('.sidebar .news-item');
$this->assertEquals(3, count($newsEls), 'Shows three items');
$news1LinkEls = $newsEls[0]->xpath('.//a'); // relative xpath
$this->assertEquals(
'My first news',
(string)$news1LinkEls[0],
'News item link contains correct title'
);
}
}
Wednesday, 17 November 2010
WRITE FLEXIBLE INTEGRATIONTESTS
Learn XPath (or use a CSS to XPath converter)
Learn SimpleXML (built-in with PHP5)
Make few assumptions about template markup
Make assertions less brittle by using semantic markup
Wednesday, 17 November 2010
LINKS
Unit testing in SilverStripe
http://doc.silverstripe.org/testing-guide
Usage of “phpunit” executable in SilverStripe
http://goo.gl/D23KJ
Book:“Test Driven Development: By Example” (Kent Beck)
Wednesday, 17 November 2010

More Related Content

What's hot

Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
 
Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3Yi-Huan Chan
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to ProtractorJie-Wei Wu
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Roy Yu
 
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"GeeksLab Odessa
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript ApplicationsThe Rolling Scopes
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyIgor Napierala
 
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
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
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
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJSPeter Drinnan
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 

What's hot (20)

Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
Angular testing
Angular testingAngular testing
Angular testing
 
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
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
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
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
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 

Similar to Unit Testing in SilverStripe

Intro to PHP Testing
Intro to PHP TestingIntro to PHP Testing
Intro to PHP TestingRan Mizrahi
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
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
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to TestZsolt Fabok
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to heroJeremy Cook
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
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
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitJames Fuller
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your CodeNate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0Nate Abele
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9google
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 

Similar to Unit Testing in SilverStripe (20)

Intro to PHP Testing
Intro to PHP TestingIntro to PHP Testing
Intro to PHP Testing
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
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
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Google test training
Google test trainingGoogle test training
Google test training
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
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
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
PHPUnit - Unit testing
PHPUnit - Unit testingPHPUnit - Unit testing
PHPUnit - Unit testing
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Unit Testing in SilverStripe

  • 1. UNITTESTING IN SILVERSTRIPE A couple of tricks you might not know about Ingo Schommer (@chillu), October 2010 Wednesday, 17 November 2010
  • 2. MORE EXPRESSIVE ASSERTIONS Bad: Generic assertion, little debugging value <?php class MyFileCreatorTest extends FunctionalTest { function testFileGeneration() { $obj = new MyFileCreator(); $filepath = $obj->createFile(); $this->assertEquals(file_exists($filepath), true); } } 1) MyFileCreatorTest::testFileGeneration Failed asserting that <boolean:true> matches expected <boolean:false>. Wednesday, 17 November 2010
  • 3. MORE EXPRESSIVE ASSERTIONS Good: Use assertions that communicate failures better <?php class MyFileCreatorTest extends FunctionalTest { function testFileGeneration() { $obj = new MyFileCreator(); $filepath = $obj->createFile(); $this->assertFileExists($filepath); } } 1) MyFileCreatorTest::testFileGeneration Failed asserting that file "/my/path/file.txt" exists. Wednesday, 17 November 2010
  • 4. MORE EXPRESSIVE ASSERTIONS Useful built-in assertions: assertType(<string>, <object>) assertArrayHasKey(<key>, <array>) assertContains(<needle>, <haystack>) assertEmailSent($to, $from = null, $subject = null, $content = null) assertDOSContains($matches, $dataObjectSet) Useful custom assertions in SapphireTest: Wednesday, 17 November 2010
  • 5. MORE EXPRESSIVE ASSERTIONS $members = DataObject::get('Member'); $this->assertContains('test@test.com',$members->column('Email')); $member = DataObject::get_one('Member', '"Email" = 'test@test.com''); $this->assertType('Member', $member); Using assertType() Using DataObjectSet->column() Wednesday, 17 November 2010
  • 6. PHPUNIT EXECUTABLE INSTEAD OF SAKE New feature since 2.4.3, backported to 2.3.9 as well More features than proxying through “sake” CLI tool Code coverage generation in “XML Clover” format (which can be parsed by phpUnderControl and other tools) Wednesday, 17 November 2010
  • 7. PHPUNIT EXECUTABLE INSTEAD OF SAKE With “sake” phpunit . phpunit sapphire phpunit sapphire/tests/DataObjectTest.php phpunit --coverage-html assets/ sake dev/tests/all sake dev/tests/modules/sapphire sake dev/tests/DataObjectTest sake dev/tests/coverage With “phpunit” Wednesday, 17 November 2010
  • 8. PHPUNIT: RUN ALLTESTS IN A FOLDER phpunit --verbose sapphire/tests/security PHPUnit 3.5.3 by Sebastian Bergmann. sapphire/tests/security BasicAuthTest .... GroupTest ... Time: 9 seconds, Memory: 83.50Mb OK (72 tests, 286 assertions) More granular control over which tests are run Filepath autocompletion built-in on CLI Wednesday, 17 November 2010
  • 9. PHPUNIT: RUN ONLY ONETEST METHOD Less hacky than commenting out other tests Supports regular expressions phpunit --filter testDelete sapphire/tests/DataObjectTest.php PHPUnit 3.5.3 by Sebastian Bergmann. . Time: 1 second, Memory: 64.75Mb Wednesday, 17 November 2010
  • 10. FASTERTESTSTHROUGH SQLITE3 Up to 10x faster test execution¹ means “Test Driven Development” (TDD) is fun again!Thanks Andreas :) phpunit mysite/tests '' db=sqlite3 ... Time: 2:44 seconds, Memory: 113.75Mb phpunit mysite/tests ... Time: 22:56, Memory: 116.75Mb PostgreSQL Sqlite3 ¹ Internal project on SilverStripe 2.4.2, with 97 tests and 410 assertions. Postgresql and SQLite3 modules both on trunk. Wednesday, 17 November 2010
  • 11. FASTERTESTSTHROUGH SQLITE3 Needs the sqlite3 module in your project http://silverstripe.org/sqlite-database/ Simple modification in mysite/_config.php require_once('conf/ConfigureFromEnv.php'); // ... if(Director::isDev() && @$_REQUEST['db'] == 'sqlite3') { $databaseConfig['type'] = 'SQLite3Database'; } Not a complete replacement to running tests on the actual database driver, but most of the time implementations are the same. Wednesday, 17 November 2010
  • 12. DEBUGGING A FIXTURE YAML fixtures are more concise than SQL inserts Problem: You have to run queries and joins in your head Wednesday, 17 November 2010
  • 13. DEBUGGING A FIXTURE For more complex data models, looking at SQL can be easier SilverStripe lets you load aYAML fixture into a temporary database through http://localhost/dev/tests/startsession Wednesday, 17 November 2010
  • 14. SEPARATE INTEGRATION AND UNITTESTS A UnitTest (SapphireTest class) covers an isolated aspect of a class, e.g. one method call. An IntegrationTest (FunctionalTest class) tests the sum of its parts, in SilverStripe mostly HTTP requests and their HTML responses. Wednesday, 17 November 2010
  • 15. SEPARATE INTEGRATION AND UNITTESTS Unit and IntegrationTests complement each other, both are necessary and have different intentions. Good practice: Separate tests into different folders. Example: mysite/tests/unit and mysite/tests/integration Idea: Run coverage reports separately for unit and integration tests Wednesday, 17 November 2010
  • 16. WRITE QUALITYTESTS Lack of test coverage points to problems, but high coverage doesn’t automatically mean quality code class HomepageTest extends FunctionalTest { function testResponse() { $response = $this->get('home'); $this->assertNotNull($response->getBody()); $this->assertEquals($response->getStatusCode(200)); } } Probably gives you 80% code coverage for a Homepage class, but failures don’t tell you anything useful. Bad example: Wednesday, 17 November 2010
  • 17. WRITE QUALITYTESTS High code coverage is the side effect of writing quality tests, not a goal in itself. Recommendation: Strive for high unit test coverage, and highlevel “smoke tests” through integration tests Wednesday, 17 November 2010
  • 18. WRITE FLEXIBLE INTEGRATIONTESTS <div class="sidebar"> <ul> <li class="news-item"> <a href="mylink">My first news</a> </li> <!-- ... --> </ul> </div> class HomepageTest extends FunctionalTest { function testSidebarShowsLatestNews() { $response = $this->get('home'); $newsEls = $response->cssParser()->getBySelector('.sidebar .news-item'); $this->assertEquals(3, count($newsEls), 'Shows three items'); $news1LinkEls = $newsEls[0]->xpath('.//a'); // relative xpath $this->assertEquals( 'My first news', (string)$news1LinkEls[0], 'News item link contains correct title' ); } } Wednesday, 17 November 2010
  • 19. WRITE FLEXIBLE INTEGRATIONTESTS Learn XPath (or use a CSS to XPath converter) Learn SimpleXML (built-in with PHP5) Make few assumptions about template markup Make assertions less brittle by using semantic markup Wednesday, 17 November 2010
  • 20. LINKS Unit testing in SilverStripe http://doc.silverstripe.org/testing-guide Usage of “phpunit” executable in SilverStripe http://goo.gl/D23KJ Book:“Test Driven Development: By Example” (Kent Beck) Wednesday, 17 November 2010