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 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-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-webperfNew 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 Chefdefrag2
 
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

Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 

Último (20)

Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 

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