SlideShare a Scribd company logo
1 of 27
Download to read offline
Sudar Muthu | @sudarmuthu #WCPune
Unit Testing For
WordPress
WordCamp Pune, 2015
Sudar Muthu
http://sudarmuthu.com
https://github.com/sudar
Sudar Muthu | @sudarmuthu #WCPune
Me
• Programming in PHP for more than a decade and in
WordPress for about 8 years.
• Big fan of automating process and workflows.
• Contributor to a couple of open source projects.
• Remote worker at 10up (and yes 10up is hiring :) )
Sudar Muthu | @sudarmuthu #WCPune
What about you?
• What is your typical development environment?
• What is your experience with PHP and WordPress?
• What is your experience with Unit Testing?
• What are your expectations out of this talk?
Sudar Muthu | @sudarmuthu #WCPune
Unit Testing
Credit: https://twitter.com/alistratov/status/599109195548459009
Sudar Muthu | @sudarmuthu #WCPune
Is there something wrong?
class Sample {
protected $value;
public function initialise($value) {
$this->value = $value;
}
public function execute() {
if (!$this->value) {
throw new Exception("value not set");
}
return $value * 10; // business logic
}
}
$sample = new Sample;
$sample->execute();
Sudar Muthu | @sudarmuthu #WCPune
Finding bugs is not
easy
Sudar Muthu | @sudarmuthu #WCPune
Write Tests
Sudar Muthu | @sudarmuthu #WCPune
Write Tests
It sounds obvious but getting started is the hardest part!
Sudar Muthu | @sudarmuthu #WCPune
Different types of Testing
• Functionality testing
• Integration testing
• Unit testing
Sudar Muthu | @sudarmuthu #WCPune
Different types of Testing
• Functionality testing
• Integration testing
• Unit testing
Sudar Muthu | @sudarmuthu #WCPune
Briefly
• What is PHPUnit?
• Installing PHPUnit
• Setting up folder structure
• phpunit.xml
Sudar Muthu | @sudarmuthu #WCPune
Three steps in test cases
• setup
• act
• verify
Sudar Muthu | @sudarmuthu #WCPune
Demo
Sudar Muthu | @sudarmuthu #WCPune
Writing our first test case
public function test_execute_works_with_initialise() {
// setup
$sample = new Sample();
// act
$sample->initialise(10);
$return = $sample->execute();
// verify
$this->assertEquals(100, $return);
}
Sudar Muthu | @sudarmuthu #WCPune
Testing Exception
/**
* @expectedException Exception
*/
public function test_execute_needs_initialise() {
// setup
$sample = new Sample();
// act
$sample->execute();
// verify
// that it throws and exception
}
Sudar Muthu | @sudarmuthu #WCPune
Let’s add more tests
• Testing decimals
• Testing with negative values
• Testing it work with zero
Sudar Muthu | @sudarmuthu #WCPune
Unit Testing
WordPress Code
Sudar Muthu | @sudarmuthu #WCPune
What should be tested?
function my_permalink_function( $post_id ) {
$permalink = get_permalink( absint( $post_id ) );
$permalink = apply_filters( 'special_filter', $permalink );
do_action( 'special_action', $permalink );
return $permalink;
}
Sudar Muthu | @sudarmuthu #WCPune
Don’t test the WordPress
built-in function
Sudar Muthu | @sudarmuthu #WCPune
Don’t test the WordPress
built-in function
Use Mocks instead
https://github.com/10up/wp_mock
Sudar Muthu | @sudarmuthu #WCPune
Mocking WordPress function
WP_Mock::wpFunction( 'get_permalink', array(
'args' => 42,
'times' => 1,
'return' => 'http://example.com/foo'
) );
Sudar Muthu | @sudarmuthu #WCPune
Mocking WordPress filter
WP_Mock::onFilter( 'special_filter' )
->with( 'http://example.com/foo' )
->reply( 'https://example.com/bar' );
Sudar Muthu | @sudarmuthu #WCPune
Mocking WordPress action
WP_Mock::expectAction(
'special_action',
'https://example.com/bar'
);
Sudar Muthu | @sudarmuthu #WCPune
Putting it all together
public function test_my_permalink_function() {
WP_Mock::wpFunction( 'get_permalink', array(
'args' => 42,
'times' => 1,
'return' => 'http://example.com/foo'
) );
WP_Mock::wpPassthruFunction( 'absint', array( 'times' => 1 ) );
WP_Mock::onFilter( 'special_filter' )
->with( 'http://example.com/foo' )
->reply( 'https://example.com/bar' );
WP_Mock::expectAction( 'special_action', 'https://example.com/bar' );
$result = my_permalink_function( 42 );
$this->assertEquals( 'https://example.com/bar', $result );
}
Sudar Muthu | @sudarmuthu #WCPune
Some PHPUnit Tips
• Have a fast test suite
• Use Composer
• Enable code coverage in reports
• phpunit.xml.dist vs phpunit.xml
• Use specific assertions
• Check out Unit tests in WordPress core
Sudar Muthu | @sudarmuthu #WCPune
WordPress plugin
skeleton with Tests
Use yo generator
https://github.com/10up/generator-wp-make
Sudar Muthu | @sudarmuthu #WCPune
Thank You
@sudarmuthu
http://sudarmuthu.com
https://github.com/sudar

More Related Content

What's hot

Agile2016: Exploratory Testing an API
Agile2016: Exploratory Testing an APIAgile2016: Exploratory Testing an API
Agile2016: Exploratory Testing an APIMaaret Pyhäjärvi
 
[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기
[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기
[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기CONNECT FOUNDATION
 
Rails Testing
Rails TestingRails Testing
Rails Testingmikeblake
 
Making cross browser tests beautiful
Making cross browser tests beautifulMaking cross browser tests beautiful
Making cross browser tests beautifulMeaghan Lewis
 
[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠
[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠
[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠CONNECT FOUNDATION
 
Making Software Management tools work for you - 2011 PHPBenelux Conference
Making Software Management tools work for you - 2011 PHPBenelux ConferenceMaking Software Management tools work for you - 2011 PHPBenelux Conference
Making Software Management tools work for you - 2011 PHPBenelux ConferenceJohn Mertic
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, SuccessfullySauce Labs
 
Selenium Testing with TestingBot.com
Selenium Testing with TestingBot.comSelenium Testing with TestingBot.com
Selenium Testing with TestingBot.comtestingbot
 

What's hot (12)

JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Agile2016: Exploratory Testing an API
Agile2016: Exploratory Testing an APIAgile2016: Exploratory Testing an API
Agile2016: Exploratory Testing an API
 
[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기
[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기
[부스트캠프 Tech Talk] 진명훈_datasets로 협업하기
 
Rails Testing
Rails TestingRails Testing
Rails Testing
 
Making cross browser tests beautiful
Making cross browser tests beautifulMaking cross browser tests beautiful
Making cross browser tests beautiful
 
[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠
[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠
[부스트캠프 Tech Talk] 고지형_내 자식 하나쯤은 있어야죠
 
Js unit testing
Js unit testingJs unit testing
Js unit testing
 
Making Software Management tools work for you - 2011 PHPBenelux Conference
Making Software Management tools work for you - 2011 PHPBenelux ConferenceMaking Software Management tools work for you - 2011 PHPBenelux Conference
Making Software Management tools work for you - 2011 PHPBenelux Conference
 
Automated tests
Automated testsAutomated tests
Automated tests
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, Successfully
 
Selenium Testing with TestingBot.com
Selenium Testing with TestingBot.comSelenium Testing with TestingBot.com
Selenium Testing with TestingBot.com
 

Similar to Unit testing for WordPress

WordPress Developer tools
WordPress Developer toolsWordPress Developer tools
WordPress Developer toolsSudar Muthu
 
JavaScript code generator with Yeoman
JavaScript code generator with YeomanJavaScript code generator with Yeoman
JavaScript code generator with Yeomantomi vanek
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifePeter Gfader
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptxTamas Rev
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriverTechWell
 
おっぴろげJavaEE DevOps
おっぴろげJavaEE DevOpsおっぴろげJavaEE DevOps
おっぴろげJavaEE DevOpsTaiichilow Nagase
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Mark Niebergall
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to KnowVaidas Pilkauskas
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015CiaranMcNulty
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Mike Schinkel
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 

Similar to Unit testing for WordPress (20)

WordPress Developer tools
WordPress Developer toolsWordPress Developer tools
WordPress Developer tools
 
JavaScript code generator with Yeoman
JavaScript code generator with YeomanJavaScript code generator with Yeoman
JavaScript code generator with Yeoman
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
 
Physical web
Physical webPhysical web
Physical web
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriver
 
おっぴろげJavaEE DevOps
おっぴろげJavaEE DevOpsおっぴろげJavaEE DevOps
おっぴろげJavaEE DevOps
 
Unit testing basics
Unit testing basicsUnit testing basics
Unit testing basics
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Developer Tests - Things to Know
Developer Tests - Things to KnowDeveloper Tests - Things to Know
Developer Tests - Things to Know
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 

More from Sudar Muthu

A quick preview of WP CLI - Chennai WordPress Meetup
A quick preview of WP CLI - Chennai WordPress MeetupA quick preview of WP CLI - Chennai WordPress Meetup
A quick preview of WP CLI - Chennai WordPress MeetupSudar Muthu
 
Using arduino and raspberry pi for internet of things
Using arduino and raspberry pi for internet of thingsUsing arduino and raspberry pi for internet of things
Using arduino and raspberry pi for internet of thingsSudar Muthu
 
How arduino helped me in life
How arduino helped me in lifeHow arduino helped me in life
How arduino helped me in lifeSudar Muthu
 
Having fun with hardware
Having fun with hardwareHaving fun with hardware
Having fun with hardwareSudar Muthu
 
Getting started with arduino workshop
Getting started with arduino workshopGetting started with arduino workshop
Getting started with arduino workshopSudar Muthu
 
Python in raspberry pi
Python in raspberry piPython in raspberry pi
Python in raspberry piSudar Muthu
 
Hack 101 at IIT Kanpur
Hack 101 at IIT KanpurHack 101 at IIT Kanpur
Hack 101 at IIT KanpurSudar Muthu
 
PureCSS open hack 2013
PureCSS open hack 2013PureCSS open hack 2013
PureCSS open hack 2013Sudar Muthu
 
Arduino Robotics workshop day2
Arduino Robotics workshop day2Arduino Robotics workshop day2
Arduino Robotics workshop day2Sudar Muthu
 
Arduino Robotics workshop Day1
Arduino Robotics workshop Day1Arduino Robotics workshop Day1
Arduino Robotics workshop Day1Sudar Muthu
 
Hands on Hadoop and pig
Hands on Hadoop and pigHands on Hadoop and pig
Hands on Hadoop and pigSudar Muthu
 
Lets make robots
Lets make robotsLets make robots
Lets make robotsSudar Muthu
 
Capabilities of Arduino (including Due)
Capabilities of Arduino (including Due)Capabilities of Arduino (including Due)
Capabilities of Arduino (including Due)Sudar Muthu
 
Controlling robots using javascript
Controlling robots using javascriptControlling robots using javascript
Controlling robots using javascriptSudar Muthu
 
Picture perfect hacks with flickr API
Picture perfect hacks with flickr APIPicture perfect hacks with flickr API
Picture perfect hacks with flickr APISudar Muthu
 
Capabilities of Arduino
Capabilities of ArduinoCapabilities of Arduino
Capabilities of ArduinoSudar Muthu
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Using Javascript in today's world
Using Javascript in today's worldUsing Javascript in today's world
Using Javascript in today's worldSudar Muthu
 

More from Sudar Muthu (20)

A quick preview of WP CLI - Chennai WordPress Meetup
A quick preview of WP CLI - Chennai WordPress MeetupA quick preview of WP CLI - Chennai WordPress Meetup
A quick preview of WP CLI - Chennai WordPress Meetup
 
Using arduino and raspberry pi for internet of things
Using arduino and raspberry pi for internet of thingsUsing arduino and raspberry pi for internet of things
Using arduino and raspberry pi for internet of things
 
How arduino helped me in life
How arduino helped me in lifeHow arduino helped me in life
How arduino helped me in life
 
Having fun with hardware
Having fun with hardwareHaving fun with hardware
Having fun with hardware
 
Getting started with arduino workshop
Getting started with arduino workshopGetting started with arduino workshop
Getting started with arduino workshop
 
Python in raspberry pi
Python in raspberry piPython in raspberry pi
Python in raspberry pi
 
Hack 101 at IIT Kanpur
Hack 101 at IIT KanpurHack 101 at IIT Kanpur
Hack 101 at IIT Kanpur
 
PureCSS open hack 2013
PureCSS open hack 2013PureCSS open hack 2013
PureCSS open hack 2013
 
Pig workshop
Pig workshopPig workshop
Pig workshop
 
Arduino Robotics workshop day2
Arduino Robotics workshop day2Arduino Robotics workshop day2
Arduino Robotics workshop day2
 
Arduino Robotics workshop Day1
Arduino Robotics workshop Day1Arduino Robotics workshop Day1
Arduino Robotics workshop Day1
 
Hands on Hadoop and pig
Hands on Hadoop and pigHands on Hadoop and pig
Hands on Hadoop and pig
 
Lets make robots
Lets make robotsLets make robots
Lets make robots
 
Capabilities of Arduino (including Due)
Capabilities of Arduino (including Due)Capabilities of Arduino (including Due)
Capabilities of Arduino (including Due)
 
Controlling robots using javascript
Controlling robots using javascriptControlling robots using javascript
Controlling robots using javascript
 
Picture perfect hacks with flickr API
Picture perfect hacks with flickr APIPicture perfect hacks with flickr API
Picture perfect hacks with flickr API
 
Hacking 101
Hacking 101Hacking 101
Hacking 101
 
Capabilities of Arduino
Capabilities of ArduinoCapabilities of Arduino
Capabilities of Arduino
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Using Javascript in today's world
Using Javascript in today's worldUsing Javascript in today's world
Using Javascript in today's world
 

Recently uploaded

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Recently uploaded (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Unit testing for WordPress

  • 1. Sudar Muthu | @sudarmuthu #WCPune Unit Testing For WordPress WordCamp Pune, 2015 Sudar Muthu http://sudarmuthu.com https://github.com/sudar
  • 2. Sudar Muthu | @sudarmuthu #WCPune Me • Programming in PHP for more than a decade and in WordPress for about 8 years. • Big fan of automating process and workflows. • Contributor to a couple of open source projects. • Remote worker at 10up (and yes 10up is hiring :) )
  • 3. Sudar Muthu | @sudarmuthu #WCPune What about you? • What is your typical development environment? • What is your experience with PHP and WordPress? • What is your experience with Unit Testing? • What are your expectations out of this talk?
  • 4. Sudar Muthu | @sudarmuthu #WCPune Unit Testing Credit: https://twitter.com/alistratov/status/599109195548459009
  • 5. Sudar Muthu | @sudarmuthu #WCPune Is there something wrong? class Sample { protected $value; public function initialise($value) { $this->value = $value; } public function execute() { if (!$this->value) { throw new Exception("value not set"); } return $value * 10; // business logic } } $sample = new Sample; $sample->execute();
  • 6. Sudar Muthu | @sudarmuthu #WCPune Finding bugs is not easy
  • 7. Sudar Muthu | @sudarmuthu #WCPune Write Tests
  • 8. Sudar Muthu | @sudarmuthu #WCPune Write Tests It sounds obvious but getting started is the hardest part!
  • 9. Sudar Muthu | @sudarmuthu #WCPune Different types of Testing • Functionality testing • Integration testing • Unit testing
  • 10. Sudar Muthu | @sudarmuthu #WCPune Different types of Testing • Functionality testing • Integration testing • Unit testing
  • 11. Sudar Muthu | @sudarmuthu #WCPune Briefly • What is PHPUnit? • Installing PHPUnit • Setting up folder structure • phpunit.xml
  • 12. Sudar Muthu | @sudarmuthu #WCPune Three steps in test cases • setup • act • verify
  • 13. Sudar Muthu | @sudarmuthu #WCPune Demo
  • 14. Sudar Muthu | @sudarmuthu #WCPune Writing our first test case public function test_execute_works_with_initialise() { // setup $sample = new Sample(); // act $sample->initialise(10); $return = $sample->execute(); // verify $this->assertEquals(100, $return); }
  • 15. Sudar Muthu | @sudarmuthu #WCPune Testing Exception /** * @expectedException Exception */ public function test_execute_needs_initialise() { // setup $sample = new Sample(); // act $sample->execute(); // verify // that it throws and exception }
  • 16. Sudar Muthu | @sudarmuthu #WCPune Let’s add more tests • Testing decimals • Testing with negative values • Testing it work with zero
  • 17. Sudar Muthu | @sudarmuthu #WCPune Unit Testing WordPress Code
  • 18. Sudar Muthu | @sudarmuthu #WCPune What should be tested? function my_permalink_function( $post_id ) { $permalink = get_permalink( absint( $post_id ) ); $permalink = apply_filters( 'special_filter', $permalink ); do_action( 'special_action', $permalink ); return $permalink; }
  • 19. Sudar Muthu | @sudarmuthu #WCPune Don’t test the WordPress built-in function
  • 20. Sudar Muthu | @sudarmuthu #WCPune Don’t test the WordPress built-in function Use Mocks instead https://github.com/10up/wp_mock
  • 21. Sudar Muthu | @sudarmuthu #WCPune Mocking WordPress function WP_Mock::wpFunction( 'get_permalink', array( 'args' => 42, 'times' => 1, 'return' => 'http://example.com/foo' ) );
  • 22. Sudar Muthu | @sudarmuthu #WCPune Mocking WordPress filter WP_Mock::onFilter( 'special_filter' ) ->with( 'http://example.com/foo' ) ->reply( 'https://example.com/bar' );
  • 23. Sudar Muthu | @sudarmuthu #WCPune Mocking WordPress action WP_Mock::expectAction( 'special_action', 'https://example.com/bar' );
  • 24. Sudar Muthu | @sudarmuthu #WCPune Putting it all together public function test_my_permalink_function() { WP_Mock::wpFunction( 'get_permalink', array( 'args' => 42, 'times' => 1, 'return' => 'http://example.com/foo' ) ); WP_Mock::wpPassthruFunction( 'absint', array( 'times' => 1 ) ); WP_Mock::onFilter( 'special_filter' ) ->with( 'http://example.com/foo' ) ->reply( 'https://example.com/bar' ); WP_Mock::expectAction( 'special_action', 'https://example.com/bar' ); $result = my_permalink_function( 42 ); $this->assertEquals( 'https://example.com/bar', $result ); }
  • 25. Sudar Muthu | @sudarmuthu #WCPune Some PHPUnit Tips • Have a fast test suite • Use Composer • Enable code coverage in reports • phpunit.xml.dist vs phpunit.xml • Use specific assertions • Check out Unit tests in WordPress core
  • 26. Sudar Muthu | @sudarmuthu #WCPune WordPress plugin skeleton with Tests Use yo generator https://github.com/10up/generator-wp-make
  • 27. Sudar Muthu | @sudarmuthu #WCPune Thank You @sudarmuthu http://sudarmuthu.com https://github.com/sudar