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

Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3
Yi-Huan Chan
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 

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 Testing
Ran Mizrahi
 
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
Michelangelo van Dam
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
google
 

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

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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