SlideShare a Scribd company logo
1 of 50
Getting Started with
PHPUnit
Matt Frost
http://joind.in/13536
@shrtwhitebldguy
Who am I?
• Director of Engineering at Budget Dumpster
• Marathoner (4 marathoner)
• Dad of 2 awesome little people
• Open Source Project Creator/Contributor
• Loosely Coupled Podcast Co-Host
• Testing advocate
• Agile skeptic
What Can I Expect?
• Coverage of essential PHPUnit concepts
• Practical examples/code along sessions
• Just enough theory
• Assertions, Mocking, Setup, Tear Down, Test suite
structure, Dependency Injection, Code Coverage;
to name a few things.
• https://github.com/mfrost503/phpunit-tutorial
Finally…
• My aim is give you something you can take back
to work with you,
• …provide assistance working through real world
examples,
• …and provide you a reference resource to help
you get started testing.
Let’s get going!
Take a few minutes to get your environment setup if you haven’t
already. Raise your hand if you need some help getting started!
Why write unit tests?
Predictability
• Helps you KNOW that things work
• Helps teammates know things work
• Makes deployment automation easier
• Allows you to go home on time
• Useful as a debugging tool
Mostly though…
It’s because you care and caring is good!
A little history
• Created by Sebastian Bergmann
• Version 1.0.0 was released April 8th, 2001
• PHP gets a bad wrap, QA/QC have helped
make it a sustainable language.
• PHP runs almost 3/4 of all web apps
• People like to know their stuff is broken before
someone else points it out to them.
Why PHPUnit?
• Most PHP projects use it
• It’s actively maintained and adapted
• There’s really not a better option for Unit Tests
• It does more than Unit Tests (there are better
options)
• Most testing resources in PHP assume PHPUnit
as the testing framework
Show me the goods!
ok…
Testable Code
• Dependency Injection
• Separation of Concerns
• Proper Use of Access Modifiers (public, private, protected,
final)
• Building with composition and useful inheritance
• All these things are going to make testing your code
easier, more reliable and more fun!
Dependency Injection
• Utilize existing functionality by passing it in!
• Eliminate the “new” keyword in method bodies
• Each component can be individually tested
• Creates flexibility for the different types of
functionality (interfaces, Liskov, etc)
Example Time!
Example from Snaggle
Assertions
• Define what we expect our code to do
• If they fail, the test fails
• Different types of assertions handle different
scenarios
• There’s more than true/false/equals!
Examples
assertTrue($condition,string $message);
$this->assertTrue(is_numeric(1));
assertFalse($condition, string $message);
$this->assertFalse(is_string(1234));
assertStringStartsWith($prefix, $string, $message);
$this->assertStringStartsWith(“pic”, “picture”);
assertSame($expected, $actual, $message);
$this->assertSame(‘1234’, ‘1234’);
assertObjectHasAttribute($attribute, $object, $message);
$this->assertObjectHasAttribute(‘name’, new User);
assertInstanceOf($expected, $actual, $message);
$this->assertInstanceOf(‘PDO’, $pdo);
assertEquals($expected, $actual, $message);
$this->assertEquals(10, $sum);
Finally some code!
Take a look at the following files:
src/Math/Addition.php
tests/Math/AdditionTest.php
Write a test!
To start, we want to write a test that verifies that
our code is adding the numbers in the array
correctly.
Take a few minutes to do that, I’ll be walking
around if you have any questions
Exceptions
@expectedException annotation in the docblock
$this->setExpectedException($exception);
Data Providers
@dataProvider <methodName>
Here’s an example!
public function numberProvider()
{
return [
[1, 2, 3],
[2, 3, 4],
[4, 5, 6]
];
}
/**
* @dataProvider numberProvider
public function testNumbers($num1, $num2, $num3)
{
Add tests
Take a look at the code. Other than returning the
correct answer, what are some other things that
can happen?
Write some tests to verify the other behaviors
Serializers and Interfaces
Data Serialization
The transformation of data from a certain format to
another format
Common types
• JSON
• PHP Array
• PHP Object
• serialize()
• json_encode()
• json_decode()
A Word on Interfaces
Serializers are a good example for interfaces,
since the need to transform data to a from
different formats is a common need.
Contracts
By adhering to a contract, the serializer types can
be interchanged as needed and type hinted on the
interface
Serializer Tests
If you look at src/Tutorial/Serializers - you will see
a number of different types. Write some tests for
them
Cue the Jeopardy Theme
src/Tutorial/Serializers
tests/Tutorial/Serializers
Communicating with data
stores
• Don’t connect to them
• Don’t talk to them
• Don’t expect them to be available
• Don’t expect data to be there
In the context of your tests, dependencies are
strangers and shouldn’t trust them.
You see…
• Using actual data sources means your tests
expect a certain state
• If source is down, tests fail…tells us nothing
about our code
• These are unit tests, we want them to run
quickly
• Ever seen an API with a 10 sec response time?
I have, they exist…
It’s not fanatical dogma
You will hate testing
and that’s not what we want
Test Doubles
• The act of replicating dependencies
• We model them for scenarios
• We use them to avoid strangers
• We know them because we make them
What can we mock?
• API calls
• Database calls
• Internal functions*
* we can use runkit to change how internal
functions like mail interact in the test
What about the data?
How?
• Data Fixtures
• Predefined responses
• Data providers
• Data fixtures are realistic data that is read into a
test to simulate an actual response
It only works if it’s
realistic
• Model realistic responses
• Save an API/DB/Cache call to a file
• Read it in, have the mock return it
• It’s that easy!
Sometimes…
There is no response and we just need to fill a
parameter requirement or we just want to make
sure a method in a dependency is called
Components
• Method - what method are we mocking
• Expectation - how often do we expect it to be called
• Parameters - what does it need to be called with?
• Return - Is it going to return data?
Example
$pdoMock = $this->getMock(‘PDO’);
$statement = $this->getMock(‘PDOStatement’);
$pdoMock->expects($this->once())
->method(‘prepare’)
->with(“SELECT * from table”)
->will($this->returnValue($statement));
That’s all there is too it
So when we run this code, we are mocking a
prepared statement in PDO
We can mock PDO Statement to handle the retrieval
of data
Let’s give it a go!
Have a look at:
src/Tutorial/Mocking/PDO
Try to write some tests for these classes
Did you notice?
We could very easily add a second parameter and
serialize the return data into our User value object.
In which case, we could choose to mock or not
mock the serializer.
API Mocking
• Guzzle
• Slack API
• Practice Mocking Guzzle
• GuzzleHttpClient
• GuzzleHttpMessageResponse
Exceptions
There are some example tests, finish the tests -
looking for exceptions!
Code Coverage Report
• Different output formats
• Analyze how completely you’ve tested
• Can be used to find testing gaps
• 100% shouldn’t be your primary goal - write
tests that make sense, not just to up coverage
Generating Reports
• vendor/bin/phpunit —coverage-html <location>
• Must have xdebug installed to generate reports
• Make sure you generate them to a directory in your
gitignore.

More Related Content

What's hot

C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)David McCarter
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practicesTan Tran
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practicesmh_azad
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPRobertGonzalez
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit TestingWen-Tien Chang
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guidelineDhananjaysinh Jhala
 
Code reviews
Code reviewsCode reviews
Code reviewsRoger Xia
 
Understanding Typing. Understanding Ruby.
Understanding Typing. Understanding Ruby.Understanding Typing. Understanding Ruby.
Understanding Typing. Understanding Ruby.Justin Lin
 
Extracts from "Clean code"
Extracts from "Clean code"Extracts from "Clean code"
Extracts from "Clean code"VlatkaPavii
 
Python introduction
Python introductionPython introduction
Python introductionRoger Xia
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best PracticesAnsar Ahmed
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesEdorian
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureNick Pruehs
 
Behaviour-Driven Development for Conversational Applications
Behaviour-Driven Development for Conversational ApplicationsBehaviour-Driven Development for Conversational Applications
Behaviour-Driven Development for Conversational ApplicationsFlorian Georg
 

What's hot (18)

C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Code reviews
Code reviewsCode reviews
Code reviews
 
OOP Day 2
OOP Day 2OOP Day 2
OOP Day 2
 
OOP Day 1
OOP Day 1OOP Day 1
OOP Day 1
 
Coding standard
Coding standardCoding standard
Coding standard
 
Understanding Typing. Understanding Ruby.
Understanding Typing. Understanding Ruby.Understanding Typing. Understanding Ruby.
Understanding Typing. Understanding Ruby.
 
Extracts from "Clean code"
Extracts from "Clean code"Extracts from "Clean code"
Extracts from "Clean code"
 
Python introduction
Python introductionPython introduction
Python introduction
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & Structure
 
Behaviour-Driven Development for Conversational Applications
Behaviour-Driven Development for Conversational ApplicationsBehaviour-Driven Development for Conversational Applications
Behaviour-Driven Development for Conversational Applications
 

Similar to Getting started-php unit

If you want to automate, you learn to code
If you want to automate, you learn to codeIf you want to automate, you learn to code
If you want to automate, you learn to codeAlan Richardson
 
Finding Needles in Haystacks
Finding Needles in HaystacksFinding Needles in Haystacks
Finding Needles in Haystackssnyff
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Uma Ghotikar
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Ortus Solutions, Corp
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticLB Denker
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven developmentEinar Ingebrigtsen
 
Working with Legacy Code
Working with Legacy CodeWorking with Legacy Code
Working with Legacy CodeEyal Golan
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Learn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshopLearn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshopchartjes
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateLB Denker
 
Automated Testing but like for PowerShell (April 2012)
Automated Testing but like for PowerShell (April 2012)Automated Testing but like for PowerShell (April 2012)
Automated Testing but like for PowerShell (April 2012)Rob Reynolds
 
Clean tests
Clean testsClean tests
Clean testsAgileee
 
Fuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox TestingFuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox TestingNetSPI
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingTim Duckett
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0Ganesh Kondal
 
How do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for DevelopersHow do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for DevelopersIvo Andreev
 

Similar to Getting started-php unit (20)

Performance Tuning with XHProf
Performance Tuning with XHProfPerformance Tuning with XHProf
Performance Tuning with XHProf
 
If you want to automate, you learn to code
If you want to automate, you learn to codeIf you want to automate, you learn to code
If you want to automate, you learn to code
 
Finding Needles in Haystacks
Finding Needles in HaystacksFinding Needles in Haystacks
Finding Needles in Haystacks
 
Enterprise PHP
Enterprise PHPEnterprise PHP
Enterprise PHP
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven development
 
Working with Legacy Code
Working with Legacy CodeWorking with Legacy Code
Working with Legacy Code
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Learn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshopLearn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshop
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to Integrate
 
Automated Testing but like for PowerShell (April 2012)
Automated Testing but like for PowerShell (April 2012)Automated Testing but like for PowerShell (April 2012)
Automated Testing but like for PowerShell (April 2012)
 
Clean tests
Clean testsClean tests
Clean tests
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Fuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox TestingFuzzing and You: Automating Whitebox Testing
Fuzzing and You: Automating Whitebox Testing
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
How do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for DevelopersHow do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for Developers
 

More from mfrost503

Ain't Nobody Got Time For That: Intro to Automation
Ain't Nobody Got Time For That: Intro to AutomationAin't Nobody Got Time For That: Intro to Automation
Ain't Nobody Got Time For That: Intro to Automationmfrost503
 
Intro to OAuth
Intro to OAuthIntro to OAuth
Intro to OAuthmfrost503
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Agent of Change
Agent of ChangeAgent of Change
Agent of Changemfrost503
 
Agent of Change
Agent of ChangeAgent of Change
Agent of Changemfrost503
 
BDD Language in PHPUnit Tests
BDD Language in PHPUnit TestsBDD Language in PHPUnit Tests
BDD Language in PHPUnit Testsmfrost503
 

More from mfrost503 (7)

Ain't Nobody Got Time For That: Intro to Automation
Ain't Nobody Got Time For That: Intro to AutomationAin't Nobody Got Time For That: Intro to Automation
Ain't Nobody Got Time For That: Intro to Automation
 
Intro to OAuth
Intro to OAuthIntro to OAuth
Intro to OAuth
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Agent of Change
Agent of ChangeAgent of Change
Agent of Change
 
Agent of Change
Agent of ChangeAgent of Change
Agent of Change
 
BDD Language in PHPUnit Tests
BDD Language in PHPUnit TestsBDD Language in PHPUnit Tests
BDD Language in PHPUnit Tests
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

Getting started-php unit

  • 1. Getting Started with PHPUnit Matt Frost http://joind.in/13536 @shrtwhitebldguy
  • 2. Who am I? • Director of Engineering at Budget Dumpster • Marathoner (4 marathoner) • Dad of 2 awesome little people • Open Source Project Creator/Contributor • Loosely Coupled Podcast Co-Host • Testing advocate • Agile skeptic
  • 3. What Can I Expect? • Coverage of essential PHPUnit concepts • Practical examples/code along sessions • Just enough theory • Assertions, Mocking, Setup, Tear Down, Test suite structure, Dependency Injection, Code Coverage; to name a few things. • https://github.com/mfrost503/phpunit-tutorial
  • 4. Finally… • My aim is give you something you can take back to work with you, • …provide assistance working through real world examples, • …and provide you a reference resource to help you get started testing.
  • 5. Let’s get going! Take a few minutes to get your environment setup if you haven’t already. Raise your hand if you need some help getting started!
  • 6. Why write unit tests?
  • 7. Predictability • Helps you KNOW that things work • Helps teammates know things work • Makes deployment automation easier • Allows you to go home on time • Useful as a debugging tool
  • 8. Mostly though… It’s because you care and caring is good!
  • 9. A little history • Created by Sebastian Bergmann • Version 1.0.0 was released April 8th, 2001 • PHP gets a bad wrap, QA/QC have helped make it a sustainable language. • PHP runs almost 3/4 of all web apps • People like to know their stuff is broken before someone else points it out to them.
  • 10. Why PHPUnit? • Most PHP projects use it • It’s actively maintained and adapted • There’s really not a better option for Unit Tests • It does more than Unit Tests (there are better options) • Most testing resources in PHP assume PHPUnit as the testing framework
  • 11. Show me the goods! ok…
  • 12. Testable Code • Dependency Injection • Separation of Concerns • Proper Use of Access Modifiers (public, private, protected, final) • Building with composition and useful inheritance • All these things are going to make testing your code easier, more reliable and more fun!
  • 13. Dependency Injection • Utilize existing functionality by passing it in! • Eliminate the “new” keyword in method bodies • Each component can be individually tested • Creates flexibility for the different types of functionality (interfaces, Liskov, etc)
  • 15. Assertions • Define what we expect our code to do • If they fail, the test fails • Different types of assertions handle different scenarios • There’s more than true/false/equals!
  • 16. Examples assertTrue($condition,string $message); $this->assertTrue(is_numeric(1)); assertFalse($condition, string $message); $this->assertFalse(is_string(1234)); assertStringStartsWith($prefix, $string, $message); $this->assertStringStartsWith(“pic”, “picture”); assertSame($expected, $actual, $message); $this->assertSame(‘1234’, ‘1234’); assertObjectHasAttribute($attribute, $object, $message); $this->assertObjectHasAttribute(‘name’, new User); assertInstanceOf($expected, $actual, $message); $this->assertInstanceOf(‘PDO’, $pdo); assertEquals($expected, $actual, $message); $this->assertEquals(10, $sum);
  • 17. Finally some code! Take a look at the following files: src/Math/Addition.php tests/Math/AdditionTest.php
  • 18. Write a test! To start, we want to write a test that verifies that our code is adding the numbers in the array correctly. Take a few minutes to do that, I’ll be walking around if you have any questions
  • 19. Exceptions @expectedException annotation in the docblock $this->setExpectedException($exception);
  • 21. public function numberProvider() { return [ [1, 2, 3], [2, 3, 4], [4, 5, 6] ]; } /** * @dataProvider numberProvider public function testNumbers($num1, $num2, $num3) {
  • 22. Add tests Take a look at the code. Other than returning the correct answer, what are some other things that can happen? Write some tests to verify the other behaviors
  • 24. Data Serialization The transformation of data from a certain format to another format
  • 25. Common types • JSON • PHP Array • PHP Object • serialize() • json_encode() • json_decode()
  • 26. A Word on Interfaces Serializers are a good example for interfaces, since the need to transform data to a from different formats is a common need.
  • 27. Contracts By adhering to a contract, the serializer types can be interchanged as needed and type hinted on the interface
  • 28. Serializer Tests If you look at src/Tutorial/Serializers - you will see a number of different types. Write some tests for them
  • 29. Cue the Jeopardy Theme src/Tutorial/Serializers tests/Tutorial/Serializers
  • 30. Communicating with data stores • Don’t connect to them • Don’t talk to them • Don’t expect them to be available • Don’t expect data to be there
  • 31. In the context of your tests, dependencies are strangers and shouldn’t trust them.
  • 32. You see… • Using actual data sources means your tests expect a certain state • If source is down, tests fail…tells us nothing about our code • These are unit tests, we want them to run quickly • Ever seen an API with a 10 sec response time? I have, they exist…
  • 34. You will hate testing and that’s not what we want
  • 35. Test Doubles • The act of replicating dependencies • We model them for scenarios • We use them to avoid strangers • We know them because we make them
  • 36.
  • 37. What can we mock? • API calls • Database calls • Internal functions* * we can use runkit to change how internal functions like mail interact in the test
  • 38. What about the data?
  • 39. How? • Data Fixtures • Predefined responses • Data providers • Data fixtures are realistic data that is read into a test to simulate an actual response
  • 40. It only works if it’s realistic • Model realistic responses • Save an API/DB/Cache call to a file • Read it in, have the mock return it • It’s that easy!
  • 41. Sometimes… There is no response and we just need to fill a parameter requirement or we just want to make sure a method in a dependency is called
  • 42. Components • Method - what method are we mocking • Expectation - how often do we expect it to be called • Parameters - what does it need to be called with? • Return - Is it going to return data?
  • 43. Example $pdoMock = $this->getMock(‘PDO’); $statement = $this->getMock(‘PDOStatement’); $pdoMock->expects($this->once()) ->method(‘prepare’) ->with(“SELECT * from table”) ->will($this->returnValue($statement));
  • 44. That’s all there is too it So when we run this code, we are mocking a prepared statement in PDO We can mock PDO Statement to handle the retrieval of data
  • 45. Let’s give it a go! Have a look at: src/Tutorial/Mocking/PDO Try to write some tests for these classes
  • 46. Did you notice? We could very easily add a second parameter and serialize the return data into our User value object. In which case, we could choose to mock or not mock the serializer.
  • 47. API Mocking • Guzzle • Slack API • Practice Mocking Guzzle • GuzzleHttpClient • GuzzleHttpMessageResponse
  • 48. Exceptions There are some example tests, finish the tests - looking for exceptions!
  • 49. Code Coverage Report • Different output formats • Analyze how completely you’ve tested • Can be used to find testing gaps • 100% shouldn’t be your primary goal - write tests that make sense, not just to up coverage
  • 50. Generating Reports • vendor/bin/phpunit —coverage-html <location> • Must have xdebug installed to generate reports • Make sure you generate them to a directory in your gitignore.