SlideShare a Scribd company logo
1 of 30
Download to read offline
Anis Uddin Ahmad
Sr. Software Architect
Softzino Technologies
Testing in Laravel
What, why and how
(@ajaxray)
Why Automated Testing?
Doesn’t it waste valuable developer time?
Why Automated Testing?
Doesn’t it waste valuable developer time?
New Feature
Code
Test
Fixing Required
Done
Why Automated Testing?
Doesn’t it waste valuable developer time?
New Feature
Code
*Test*
Fixing Required
Change Request
Dependencies Updated
Done
Bug Reported
Why Automated Testing?
Doesn’t it waste valuable developer time?
• Reduces the time and cost of testing
• Increases the accuracy of testing
• Improves the quality of software
• Con
fi
dence of changing anytime
What to test?
The hidden question in every beginner’s mind
What to test?
Code Coverage? (how many codes are tested)
https://medium.com/@anowarhossain/code-coverage-report-in-laravel-and-make-100-coverage-of-your-code-ce27cccbc738
What to test?
Things that … you want to ensure “NOT BROKEN”
https://laraveldaily.com/post/matt-stau
ff
er-laravel-enterprise-ready
What to test?
The essential things…
• The routes - main entry points
• Authentication and authorisations
• Thing related to payment / privacy / legal issues
• Business decisions
• Third party dependencies (with mock or stub)
• Anything that have de
fi
ned expectations
Anything that you’d like to con
fi
rm after a new deployment
Perspective of testing
Let’s make a toy airplane
Individual components and how they work together
Perspective of testing
Unit Testing vs Functional Testing
Unit Testing Functional Testing
Scope Individual units of code Overall functionality of a software
Target Speci
fi
c values, conditions, returns, exceptions Ensure features and requirements
Frequency Every time any relevant code changes Every time any dependency/expectation changes
Perspective Whitebox. (Transparent) Blackbox. (Machine with opaque casing)
Testing Perspectives for a software
Agile testing strategy pyramid
Let’s write a Unit Test
Demo session
Test writing pattern - AAA
Arrange - Act - Assert
Test lifecycle
Setup and Teardown
fl
ow
tearDownAfterClass()
setUpBeforeClass()
tearDown()
setUp()
aTestCase()
EXECUTE TEST GENERATE TEST REPORT
Preparing Environment
Testing Environment !== Real Environment
Preparing Environment
Options to de
fi
ne separate con
fi
guration
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value=“false"/>
</php>
phpunit.xml
Preparing Environment
Options to de
fi
ne separate con
fi
guration
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
.env.testing
phpunit.xml
Preparing Database
Isolated and risk free version - for testing environment
<php>
...
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
...
</php>
phpunit.xml
Preparing Database
Cleanup and prepare for testing new scenario
use IlluminateFoundationTestingDatabaseMigrations;
use IlluminateFoundationTestingRefreshDatabase;
use TestsTestCase;
class HomepageTest extends TestCase
{
use DatabaseMigrations, RefreshDatabase;
public function test_something_with_predefined_data()
{
// Run the DatabaseSeeder...
$this->seed();
// Run an array of specific seeders...
$this->seed([
AreaListSeeder::class,
DocumentCategoriesSeeder::class,
]);
}
// ...
Execute Migrations before running test
Cleanup DB after running test
Stage a prede
fi
ned scenario in DB
Let’s write a Feature Test
Demo session
What can we Assert?
Various points to validate application sanity
Look into Testing/TestResponse
Check if
expected text
is showing in
page
$response = $this->actingAs($user)->get('/path');
// Find text in response page
$response->assertSee('Dashboard');
$response->assertDontSee('Admin');
// Can be used array of text, also can verify in order
$response->assertSee(['A Menu Item', 'Another Menu Item’]);
// Also can verify if they are showing in order
$response->assertSeeInOrder(['A Menu Item', 'Another Menu Item']);
// All of the above has a *Text() alternative
// that strip_tags the response before compare
$response->assertSeeText('Dashboard');
What was
passed to
the view?
public function test_it_has_the_correct_value()
{
$response = $this->get('/some-route');
$this->assertEquals('John Doe', $response->viewData('name'));
}
public function test_it_contains_a_given_record()
{
$response = $this->get('/some-route');
$this->assertTrue($response->viewData('users')->contains($userA));
}
public function test_it_returns_the_correct_amount_of_records()
{
$response = $this->get('/some-route');
$this->assertCount(10, $response->viewData('users'));
}
Code snippet source
Validating
API
Responses
$response = $this->postJson('/api/user', ['name' => 'Sally']);
// Validate Response JSON
$response
->assertStatus(201)
->assertJson(['created' => true]);
->assertJsonPath('team.owner.name', 'Darian');
// Fluent JSON Testing
$response
->assertJson(fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', 'Victoria Faith')
->where('email', fn (string $email)
=> str($email)->is('victoria@gmail.com'))
->whereNot('status', 'pending')
->missing('password')
->etc()
);
// Also there are has, hasMany, hasAll, missing, missingAll etc.
Code snippet source
Validating
Database
records
$user = User::factory()->create();
// Check model existence
$this->assertModelExists($user);
$this->assertModelMissing($user);
// SoftDeleted or not
$this->assertSoftDeleted($user);
$this->assertNotSoftDeleted($user);
// Count records
$this->assertDatabaseCount('users', 5);
// Check specific record
$this->assertDatabaseHas('users', [
'email' => 'sally@example.com',
]);
Exception
Handling
// In feature testing
$response = $this->withoutExceptionHandling()->get('/');
// Mention which exception is expected
$this->expectException(MyAccessParsingException::class);
Filtering Test
Run speci
fi
c set of tests
php artisan test
// Run Specific TestSuite
php artisan test --testsuite Unit
// Run a single class
php artisan test --filter=HomepageTest
// Run a single function
php artisan test --filter=test_home_responds_with_success_for_Admin
@ajaxray
🐦 📬{between curly brackets} 🌎 ajaxray.com

More Related Content

Similar to Testing in Laravel Framework

Rails Testing
Rails TestingRails Testing
Rails Testingmikeblake
 
WordPress Acceptance Testing, Solved!
WordPress Acceptance Testing, Solved!WordPress Acceptance Testing, Solved!
WordPress Acceptance Testing, Solved!Taylor Lovett
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Pavel Chunyayev
 
Java Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and MobileJava Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and MobileElias Nogueira
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014
Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014
Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014Rackspace Academy
 
EWD 3 Training Course Part 5a: First Steps in Building a QEWD Application
EWD 3 Training Course Part 5a: First Steps in Building a QEWD ApplicationEWD 3 Training Course Part 5a: First Steps in Building a QEWD Application
EWD 3 Training Course Part 5a: First Steps in Building a QEWD ApplicationRob Tweed
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-appsVenkata Ramana
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperfNew Relic
 
Continous delivery with Jenkins and Chef
Continous delivery with Jenkins and ChefContinous delivery with Jenkins and Chef
Continous delivery with Jenkins and Chefdefrag2
 
Test driven development (java script & mivascript)
Test driven development (java script & mivascript)Test driven development (java script & mivascript)
Test driven development (java script & mivascript)Miva
 
Atlassian's Mystique CLI, Minimizing the Experiment Development Cycle
Atlassian's Mystique CLI, Minimizing the Experiment Development CycleAtlassian's Mystique CLI, Minimizing the Experiment Development Cycle
Atlassian's Mystique CLI, Minimizing the Experiment Development CycleOptimizely
 
Open Source, infrastructure as Code, Cloud Native Apps 2015
Open Source, infrastructure as Code, Cloud Native Apps 2015Open Source, infrastructure as Code, Cloud Native Apps 2015
Open Source, infrastructure as Code, Cloud Native Apps 2015Jonas Rosland
 
DevOps and the Future of Enterprise Security
DevOps and the Future of Enterprise SecurityDevOps and the Future of Enterprise Security
DevOps and the Future of Enterprise SecurityPriyanka Aash
 
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015Codemotion
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 

Similar to Testing in Laravel Framework (20)

Rails Testing
Rails TestingRails Testing
Rails Testing
 
WordPress Acceptance Testing, Solved!
WordPress Acceptance Testing, Solved!WordPress Acceptance Testing, Solved!
WordPress Acceptance Testing, Solved!
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015
 
Java Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and MobileJava Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and Mobile
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014
Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014
Software as a Service workshop / Unlocked: the Hybrid Cloud 12th May 2014
 
EWD 3 Training Course Part 5a: First Steps in Building a QEWD Application
EWD 3 Training Course Part 5a: First Steps in Building a QEWD ApplicationEWD 3 Training Course Part 5a: First Steps in Building a QEWD Application
EWD 3 Training Course Part 5a: First Steps in Building a QEWD Application
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperf
 
Selenium
SeleniumSelenium
Selenium
 
Continous delivery with Jenkins and Chef
Continous delivery with Jenkins and ChefContinous delivery with Jenkins and Chef
Continous delivery with Jenkins and Chef
 
Monkey man
Monkey manMonkey man
Monkey man
 
Test driven development (java script & mivascript)
Test driven development (java script & mivascript)Test driven development (java script & mivascript)
Test driven development (java script & mivascript)
 
Atlassian's Mystique CLI, Minimizing the Experiment Development Cycle
Atlassian's Mystique CLI, Minimizing the Experiment Development CycleAtlassian's Mystique CLI, Minimizing the Experiment Development Cycle
Atlassian's Mystique CLI, Minimizing the Experiment Development Cycle
 
Open Source, infrastructure as Code, Cloud Native Apps 2015
Open Source, infrastructure as Code, Cloud Native Apps 2015Open Source, infrastructure as Code, Cloud Native Apps 2015
Open Source, infrastructure as Code, Cloud Native Apps 2015
 
Selenium
SeleniumSelenium
Selenium
 
DevOps and the Future of Enterprise Security
DevOps and the Future of Enterprise SecurityDevOps and the Future of Enterprise Security
DevOps and the Future of Enterprise Security
 
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
Carmen Popoviciu - Protractor styleguide | Codemotion Milan 2015
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 

More from Anis Ahmad

Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible CodeAnis Ahmad
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles Anis Ahmad
 
VCS for Teamwork - GIT Workshop
VCS for Teamwork - GIT WorkshopVCS for Teamwork - GIT Workshop
VCS for Teamwork - GIT WorkshopAnis Ahmad
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript ApplicationAnis Ahmad
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 
Caching basics in PHP
Caching basics in PHPCaching basics in PHP
Caching basics in PHPAnis Ahmad
 
Freelancing; an alternate career
Freelancing; an alternate careerFreelancing; an alternate career
Freelancing; an alternate careerAnis Ahmad
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 

More from Anis Ahmad (8)

Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
VCS for Teamwork - GIT Workshop
VCS for Teamwork - GIT WorkshopVCS for Teamwork - GIT Workshop
VCS for Teamwork - GIT Workshop
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript Application
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
Caching basics in PHP
Caching basics in PHPCaching basics in PHP
Caching basics in PHP
 
Freelancing; an alternate career
Freelancing; an alternate careerFreelancing; an alternate career
Freelancing; an alternate career
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 

Recently uploaded

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
(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
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
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
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
(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...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
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...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
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...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

Testing in Laravel Framework

  • 1. Anis Uddin Ahmad Sr. Software Architect Softzino Technologies Testing in Laravel What, why and how (@ajaxray)
  • 2. Why Automated Testing? Doesn’t it waste valuable developer time?
  • 3. Why Automated Testing? Doesn’t it waste valuable developer time? New Feature Code Test Fixing Required Done
  • 4. Why Automated Testing? Doesn’t it waste valuable developer time? New Feature Code *Test* Fixing Required Change Request Dependencies Updated Done Bug Reported
  • 5. Why Automated Testing? Doesn’t it waste valuable developer time? • Reduces the time and cost of testing • Increases the accuracy of testing • Improves the quality of software • Con fi dence of changing anytime
  • 6. What to test? The hidden question in every beginner’s mind
  • 7. What to test? Code Coverage? (how many codes are tested) https://medium.com/@anowarhossain/code-coverage-report-in-laravel-and-make-100-coverage-of-your-code-ce27cccbc738
  • 8. What to test? Things that … you want to ensure “NOT BROKEN” https://laraveldaily.com/post/matt-stau ff er-laravel-enterprise-ready
  • 9. What to test? The essential things… • The routes - main entry points • Authentication and authorisations • Thing related to payment / privacy / legal issues • Business decisions • Third party dependencies (with mock or stub) • Anything that have de fi ned expectations Anything that you’d like to con fi rm after a new deployment
  • 10. Perspective of testing Let’s make a toy airplane
  • 11. Individual components and how they work together Perspective of testing
  • 12. Unit Testing vs Functional Testing Unit Testing Functional Testing Scope Individual units of code Overall functionality of a software Target Speci fi c values, conditions, returns, exceptions Ensure features and requirements Frequency Every time any relevant code changes Every time any dependency/expectation changes Perspective Whitebox. (Transparent) Blackbox. (Machine with opaque casing)
  • 13. Testing Perspectives for a software Agile testing strategy pyramid
  • 14. Let’s write a Unit Test Demo session
  • 15. Test writing pattern - AAA Arrange - Act - Assert
  • 16. Test lifecycle Setup and Teardown fl ow tearDownAfterClass() setUpBeforeClass() tearDown() setUp() aTestCase() EXECUTE TEST GENERATE TEST REPORT
  • 18. Preparing Environment Options to de fi ne separate con fi guration <php> <env name="APP_ENV" value="testing"/> <env name="BCRYPT_ROUNDS" value="4"/> <env name="CACHE_DRIVER" value="array"/> <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value=":memory:"/> <env name="MAIL_MAILER" value="array"/> <env name="QUEUE_CONNECTION" value="sync"/> <env name="SESSION_DRIVER" value="array"/> <env name="TELESCOPE_ENABLED" value=“false"/> </php> phpunit.xml
  • 19. Preparing Environment Options to de fi ne separate con fi guration <php> <env name="APP_ENV" value="testing"/> <env name="BCRYPT_ROUNDS" value="4"/> <env name="CACHE_DRIVER" value="array"/> <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value=":memory:"/> <env name="MAIL_MAILER" value="array"/> <env name="QUEUE_CONNECTION" value="sync"/> <env name="SESSION_DRIVER" value="array"/> <env name="TELESCOPE_ENABLED" value="false"/> </php> MAIL_MAILER=smtp MAIL_HOST=mailhog MAIL_PORT=1025 .env.testing phpunit.xml
  • 20. Preparing Database Isolated and risk free version - for testing environment <php> ... <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value=":memory:"/> ... </php> phpunit.xml
  • 21. Preparing Database Cleanup and prepare for testing new scenario use IlluminateFoundationTestingDatabaseMigrations; use IlluminateFoundationTestingRefreshDatabase; use TestsTestCase; class HomepageTest extends TestCase { use DatabaseMigrations, RefreshDatabase; public function test_something_with_predefined_data() { // Run the DatabaseSeeder... $this->seed(); // Run an array of specific seeders... $this->seed([ AreaListSeeder::class, DocumentCategoriesSeeder::class, ]); } // ... Execute Migrations before running test Cleanup DB after running test Stage a prede fi ned scenario in DB
  • 22. Let’s write a Feature Test Demo session
  • 23. What can we Assert? Various points to validate application sanity Look into Testing/TestResponse
  • 24. Check if expected text is showing in page $response = $this->actingAs($user)->get('/path'); // Find text in response page $response->assertSee('Dashboard'); $response->assertDontSee('Admin'); // Can be used array of text, also can verify in order $response->assertSee(['A Menu Item', 'Another Menu Item’]); // Also can verify if they are showing in order $response->assertSeeInOrder(['A Menu Item', 'Another Menu Item']); // All of the above has a *Text() alternative // that strip_tags the response before compare $response->assertSeeText('Dashboard');
  • 25. What was passed to the view? public function test_it_has_the_correct_value() { $response = $this->get('/some-route'); $this->assertEquals('John Doe', $response->viewData('name')); } public function test_it_contains_a_given_record() { $response = $this->get('/some-route'); $this->assertTrue($response->viewData('users')->contains($userA)); } public function test_it_returns_the_correct_amount_of_records() { $response = $this->get('/some-route'); $this->assertCount(10, $response->viewData('users')); } Code snippet source
  • 26. Validating API Responses $response = $this->postJson('/api/user', ['name' => 'Sally']); // Validate Response JSON $response ->assertStatus(201) ->assertJson(['created' => true]); ->assertJsonPath('team.owner.name', 'Darian'); // Fluent JSON Testing $response ->assertJson(fn (AssertableJson $json) => $json->where('id', 1) ->where('name', 'Victoria Faith') ->where('email', fn (string $email) => str($email)->is('victoria@gmail.com')) ->whereNot('status', 'pending') ->missing('password') ->etc() ); // Also there are has, hasMany, hasAll, missing, missingAll etc. Code snippet source
  • 27. Validating Database records $user = User::factory()->create(); // Check model existence $this->assertModelExists($user); $this->assertModelMissing($user); // SoftDeleted or not $this->assertSoftDeleted($user); $this->assertNotSoftDeleted($user); // Count records $this->assertDatabaseCount('users', 5); // Check specific record $this->assertDatabaseHas('users', [ 'email' => 'sally@example.com', ]);
  • 28. Exception Handling // In feature testing $response = $this->withoutExceptionHandling()->get('/'); // Mention which exception is expected $this->expectException(MyAccessParsingException::class);
  • 29. Filtering Test Run speci fi c set of tests php artisan test // Run Specific TestSuite php artisan test --testsuite Unit // Run a single class php artisan test --filter=HomepageTest // Run a single function php artisan test --filter=test_home_responds_with_success_for_Admin
  • 30. @ajaxray 🐦 📬{between curly brackets} 🌎 ajaxray.com