SlideShare uma empresa Scribd logo
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

Mais conteúdo relacionado

Semelhante a Testing in Laravel Framework

Rails Testing
Rails TestingRails Testing
Rails Testing
mikeblake
 
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 Mizrahi
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
Pavel 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 Mobile
Elias 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 - phpbelfast
Michelangelo 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 2014
Rackspace 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 Application
Rob Tweed
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
Venkata Ramana
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperf
New Relic
 
Selenium
SeleniumSelenium
Continous delivery with Jenkins and Chef
Continous delivery with Jenkins and ChefContinous delivery with Jenkins and Chef
Continous delivery with Jenkins and Chef
defrag2
 
Monkey man
Monkey manMonkey man
Monkey man
ShapeBlue
 
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 Cycle
Optimizely
 
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
Jonas Rosland
 
Selenium
SeleniumSelenium
Selenium
Adam Goucher
 
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
Priyanka 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 2015
Codemotion
 
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
wajrcs
 

Semelhante a 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
 

Mais de Anis Ahmad

Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
Anis 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 Workshop
Anis Ahmad
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript Application
Anis 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 Ruby
Anis Ahmad
 
Caching basics in PHP
Caching basics in PHPCaching basics in PHP
Caching basics in PHP
Anis Ahmad
 
Freelancing; an alternate career
Freelancing; an alternate careerFreelancing; an alternate career
Freelancing; an alternate career
Anis Ahmad
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 

Mais de 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
 

Último

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
devvsandy
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 

Último (20)

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 

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