SlideShare a Scribd company logo
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

UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Boni Yeamin
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsUXDXConf
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
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
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
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 2024Tobias Schneck
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastUXDXConf
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
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...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
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
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 

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