SlideShare a Scribd company logo
Designing for Testability with Laravel
Derek Binkley
@DerekB_WI
About Me
★Lead Developer at National Conference of
Bar Examiners
★PHP and Java Developer
★MySQL DBA
★Father of Three
★Second ever talk
About NCBE
Examining Bars?
About NCBE
No, developing the bar exam for future lawyers.
Plus, supporting state admission authorities.
What will we cover?
What is built in to Laravel for Unit Testing
Strategies that make testing easier
Detailed examples
Unit Tests
• Lowest level of testing
• Typically done by developer
• Crucial to Test Driven Design
• Tests a Single Unit of Code and Verifies the
Results.
Why don’t developers test?
• Think code will get replaced soon.
• Think code is straightforward and won’t break.
• Tests are hard to write.
• Low perceived benefit.
• Don’t understand how to design code for
testability.
Laravel and PHPUnit
• PHPUnit Available by default
• Tests saved in Tests directory
• Tests should extend TestCase class
• Tests should be saved in file named *Test.php
• Tests method names should begin with test.
What Does Laravel Provide?
• Crawler – Gives us a mock browser/client to
run our controllers.
What Does Laravel Provide?
• Additional assertions
• ->assertResponseOk();
• ->assertResponseStatus($code);
• ->assertViewHas($key, $value = null);
• ->assertViewHasAll(array $bindings);
• ->assertViewMissing($key);
• ->assertRedirectedTo($uri, $with = []);
• ->assertRedirectedToRoute($name, $parameters = [], $with = []);
• ->assertRedirectedToAction($name, $parameters = [], $with = []);
• ->assertSessionHas($key, $value = null);
• ->assertSessionHasAll(array $bindings);
• ->assertSessionHasErrors($bindings = [], $format = null);
• ->assertHasOldInput();
Faking Data
• https://github.com/fzaninotto/Faker
• Allows us to not spend time making up test
data.
Example Form
Example Controller
Test Code – First Try
Problems?
• Database is not cleaned up. We could use
seeding in our setup and teardown methods.
• Email attempt adds a dependency upon a
network or cloud service.
• Testing all the logic of the controller at once
makes problems hard to diagnose.
Laravel Can Help
• Disabling Middleware allows testing only your controller code
• Wrapping test in a database transaction helps clean up
• Using migrations allows for resetting database to consistent
state.
How we can help ourselves
• DRY – Don’t Repeat Yourself – Be Lazy, write code once
• Single Responsibility Object – No “Jack of all Trades” Objects
• Dependency Injection – Give me what I need to do my job
• Keep cyclomatic complexity low – If there is a fork in the road
take it
• Law of Demeter – Don’t extend reach too far
• Design Patterns – Somebody has already solved our problems
Improving Our Example
• Remove dependency on session
Rerun Test and See Failure
• Remove if (is_numeric(session($user_id)))
Dependency Injection
• Pass in the objects you need
• Code to interfaces
• Avoid creating a “new” object.
• Setter Injection v. Constructor Injection
• Helps follow Law of Demeter
Arguments Against DI
• Our dependencies won’t change
• Too complex
Benefits of DI
• Can now mock objects while testing
• Test our code, not 3rd party libraries
• Loose coupling allows for easier upgrades
• Built in to Laravel
Let’s try it out
• Laravel will inject an instance of a class that is type hinted in a
constructor or method.
• Now we can use our factory anywhere within our controller.
Controller is Much Skinnier
Mock objects allow for easy controller testing
• We create a mock PersonFactory and specify
which methods will be called and what they
should return.
• Our person creation logic is now moved to a
single class (DRY), our controller can now be
tested without a database.
• Yet to test our person factory we must still
seed and clean up our database.
Repository Pattern
• Separate getting the data from the data
object.
• Code to an interface to allow for mocking.
Wrapper Around Class
• Takes class doing work as parameter
• Easy to Mock
• Won’t use underlying resources, e.g. API, to
run test.
Mocking a Facade
• The Mail class is a Laravel façade so we can
easily mock it like this.
• Laravel takes care of the rest for us.
Resources
• http://martinfowler.com/eaaCatalog/tableDataGateway.html
• https://www.youtube.com/watch?v=HhwElTL-mdI - Evan Dorn LA Ruby Meetup
• https://www.youtube.com/watch?v=X6c11niH-U8 - Chris Hartjes Ski PHP
• https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/
• https://github.com/fzaninotto/Faker
• http://laravelcoding.com/blog/laravel-5-beauty-testing
• https://laravel.com/docs/5.1/testing
• http://martinfowler.com/articles/mocksArentStubs.html
Thanks
• Derek Binkley - @DerekB_WI or dbinkley@ncbex.org
• Slides are at
http://www.slideshare.net/DerekBinkley/testing-
with-laravel
• Feedback on Joind.in at https://joind.in/talk/dc052

More Related Content

What's hot

Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Junit
JunitJunit
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Java interface
Java interfaceJava interface
Java interface
Md. Tanvir Hossain
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
Nayanda Haberty
 
TestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaTestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | Edureka
Edureka!
 
Manual testing concepts course 1
Manual testing concepts course 1Manual testing concepts course 1
Manual testing concepts course 1
Raghu Kiran
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Interview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotInterview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlot
Learning Slot
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
shaunthomas999
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
Tanmoy Roy
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
Levon Apreyan
 
Web application framework
Web application frameworkWeb application framework
Web application framework
Pankaj Chand
 

What's hot (20)

Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Junit
JunitJunit
Junit
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Java interface
Java interfaceJava interface
Java interface
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
TestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaTestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | Edureka
 
Manual testing concepts course 1
Manual testing concepts course 1Manual testing concepts course 1
Manual testing concepts course 1
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Interview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotInterview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlot
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Java Basics
Java BasicsJava Basics
Java Basics
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Web application framework
Web application frameworkWeb application framework
Web application framework
 

Similar to Testing with laravel

Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014
Red Gate Software
 
What-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptxWhat-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptx
AbhijeetKumar456867
 
Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...
SQALab
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
Meilan Ou
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
Tomaš Maconko
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
AmalEldhose2
 
Do you queue
Do you queueDo you queue
Do you queue
10n Software, LLC
 
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
Einar Ingebrigtsen
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with Laravel
Tyler Johnston
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Sahar Nofal
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
Pascal Larocque
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Md. Enamul Haque Chowdhury
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
Mayank Srivastava
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
Ganesh Kondal
 
Tools for Software Testing
Tools for Software TestingTools for Software Testing
Tools for Software Testing
Mohammed Moishin
 
Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016
Vladislav Fedorischev
 
Best practices for writing good automated tests
Best practices for writing good automated testsBest practices for writing good automated tests
Best practices for writing good automated tests
Felipe Lima
 
Clean code
Clean codeClean code
Clean code
Simon Sönnby
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
egoodwintx
 

Similar to Testing with laravel (20)

Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014
 
What-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptxWhat-is-Laravel-23-August-2017.pptx
What-is-Laravel-23-August-2017.pptx
 
Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...Generalization in Auto-Testing. How we put what we had into new Technological...
Generalization in Auto-Testing. How we put what we had into new Technological...
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
 
Do you queue
Do you queueDo you queue
Do you queue
 
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
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with Laravel
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
Tools for Software Testing
Tools for Software TestingTools for Software Testing
Tools for Software Testing
 
Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016
 
Best practices for writing good automated tests
Best practices for writing good automated testsBest practices for writing good automated tests
Best practices for writing good automated tests
 
Clean code
Clean codeClean code
Clean code
 
Unit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUGUnit Testing in R with Testthat - HRUG
Unit Testing in R with Testthat - HRUG
 

Recently uploaded

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

Testing with laravel

  • 1. Designing for Testability with Laravel Derek Binkley @DerekB_WI
  • 2. About Me ★Lead Developer at National Conference of Bar Examiners ★PHP and Java Developer ★MySQL DBA ★Father of Three ★Second ever talk
  • 4. About NCBE No, developing the bar exam for future lawyers. Plus, supporting state admission authorities.
  • 5. What will we cover? What is built in to Laravel for Unit Testing Strategies that make testing easier Detailed examples
  • 6. Unit Tests • Lowest level of testing • Typically done by developer • Crucial to Test Driven Design • Tests a Single Unit of Code and Verifies the Results.
  • 7. Why don’t developers test? • Think code will get replaced soon. • Think code is straightforward and won’t break. • Tests are hard to write. • Low perceived benefit. • Don’t understand how to design code for testability.
  • 8. Laravel and PHPUnit • PHPUnit Available by default • Tests saved in Tests directory • Tests should extend TestCase class • Tests should be saved in file named *Test.php • Tests method names should begin with test.
  • 9. What Does Laravel Provide? • Crawler – Gives us a mock browser/client to run our controllers.
  • 10. What Does Laravel Provide? • Additional assertions • ->assertResponseOk(); • ->assertResponseStatus($code); • ->assertViewHas($key, $value = null); • ->assertViewHasAll(array $bindings); • ->assertViewMissing($key); • ->assertRedirectedTo($uri, $with = []); • ->assertRedirectedToRoute($name, $parameters = [], $with = []); • ->assertRedirectedToAction($name, $parameters = [], $with = []); • ->assertSessionHas($key, $value = null); • ->assertSessionHasAll(array $bindings); • ->assertSessionHasErrors($bindings = [], $format = null); • ->assertHasOldInput();
  • 11. Faking Data • https://github.com/fzaninotto/Faker • Allows us to not spend time making up test data.
  • 14. Test Code – First Try
  • 15. Problems? • Database is not cleaned up. We could use seeding in our setup and teardown methods. • Email attempt adds a dependency upon a network or cloud service. • Testing all the logic of the controller at once makes problems hard to diagnose.
  • 16. Laravel Can Help • Disabling Middleware allows testing only your controller code • Wrapping test in a database transaction helps clean up • Using migrations allows for resetting database to consistent state.
  • 17. How we can help ourselves • DRY – Don’t Repeat Yourself – Be Lazy, write code once • Single Responsibility Object – No “Jack of all Trades” Objects • Dependency Injection – Give me what I need to do my job • Keep cyclomatic complexity low – If there is a fork in the road take it • Law of Demeter – Don’t extend reach too far • Design Patterns – Somebody has already solved our problems
  • 18. Improving Our Example • Remove dependency on session
  • 19. Rerun Test and See Failure • Remove if (is_numeric(session($user_id)))
  • 20. Dependency Injection • Pass in the objects you need • Code to interfaces • Avoid creating a “new” object. • Setter Injection v. Constructor Injection • Helps follow Law of Demeter
  • 21. Arguments Against DI • Our dependencies won’t change • Too complex
  • 22. Benefits of DI • Can now mock objects while testing • Test our code, not 3rd party libraries • Loose coupling allows for easier upgrades • Built in to Laravel
  • 23. Let’s try it out • Laravel will inject an instance of a class that is type hinted in a constructor or method. • Now we can use our factory anywhere within our controller.
  • 24. Controller is Much Skinnier
  • 25. Mock objects allow for easy controller testing • We create a mock PersonFactory and specify which methods will be called and what they should return.
  • 26. • Our person creation logic is now moved to a single class (DRY), our controller can now be tested without a database. • Yet to test our person factory we must still seed and clean up our database.
  • 27. Repository Pattern • Separate getting the data from the data object. • Code to an interface to allow for mocking.
  • 28. Wrapper Around Class • Takes class doing work as parameter • Easy to Mock • Won’t use underlying resources, e.g. API, to run test.
  • 29. Mocking a Facade • The Mail class is a Laravel façade so we can easily mock it like this. • Laravel takes care of the rest for us.
  • 30. Resources • http://martinfowler.com/eaaCatalog/tableDataGateway.html • https://www.youtube.com/watch?v=HhwElTL-mdI - Evan Dorn LA Ruby Meetup • https://www.youtube.com/watch?v=X6c11niH-U8 - Chris Hartjes Ski PHP • https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/ • https://github.com/fzaninotto/Faker • http://laravelcoding.com/blog/laravel-5-beauty-testing • https://laravel.com/docs/5.1/testing • http://martinfowler.com/articles/mocksArentStubs.html
  • 31. Thanks • Derek Binkley - @DerekB_WI or dbinkley@ncbex.org • Slides are at http://www.slideshare.net/DerekBinkley/testing- with-laravel • Feedback on Joind.in at https://joind.in/talk/dc052

Editor's Notes

  1. Common misconception. I often get asked for good drink recipes.
  2. Standardized testing takes lots of data processing. We also collect and analyze lots of “customer” data.
  3. Getting your head around what to test can be challenging. I will show you some examples of code and see how to add good tests and maybe even encourage true TDD.
  4. Integration, System and Acceptance are other higher level tests.
  5. Poll the audience. I am not going into an argument on why to test.  That gets covered a lot and is important.  In my history I have found that I don’t test because I don’t know how to write the tests. Won’t argue about what and when to test. That is up to you. If testing is easier then you will be more likely to test.
  6. We go to the route /one and look for the text – Testing a Form assertResponseOk looks for 200 return code.
  7. Builds upon PHPUnit by adding specific assertions that hide some of the Laravel “magic”
  8. Fat Controller - All logic is contained with this controller. What if we
  9. This is a very long controller just to save a simple form
  10. Explain what each test is doing and then ask for problems
  11. Does anybody see what part doesn’t get tested?
  12. Law of Demeter states you can call your own methods, methods of objects passed, methods of objects you create locally.
  13. By moving the logged in check to our middleware we can test our login logic separately.
  14. Code redirects to login without our addition of a session variable. So, we remove the if statement we can still protect our routes with middleware. Show middleware example. Explain you can now write a test for CustomAuth class.
  15. Notice comment from open source project where a developer asserts to not code to an interface because of no plans to use other implementations. Of course we all know that three years from now a cool replacement to the JWT library will be all the rage and we will want to swap that out.
  16. Fat Model, Skinny Controller
  17. This can seem silly with all of the built in magic that Eloquent provides. However by not tightly coupling our code to Eloquent it becomes more flexible and mockable. Show examples including how interface gets bound in AppServerProvider