Laravel Testing
Here we will discuss all of the ways to test your Laravel application.
Laravel Unit Testing
As you already know, unit testing's main purpose is to test particular functions of your application to make sure it works correctly in a lot of different scenarios. A good example would be testing a function that email format for an email field. The idea of unit tests is that they run quickly, and, therefore, it is faster to write unit tests than test that the function works manually.
Lavarel is coming with PHPUnit included out of the box. Moreover, the phpunit.xml
file is already included and built correctly for your application. The unit tests are in Tests/Unit/
folder and designed to test specific isolated functions of an application and execute quickly.
<?php declare(strict_types=1); use PHPUnit\Framework\TestCase; final class StackTest extends TestCase { public function testPushAndPop(): void { $stack = []; $this->assertSame(0, count($stack)); array_push($stack, 'foo'); $this->assertSame('foo', $stack[count($stack)-1]); $this->assertSame(1, count($stack)); $this->assertSame('foo', array_pop($stack)); $this->assertSame(0, count($stack)); } }
Laravel Integration Testing
Integration tests are designed to help to test the integration of different components in action, such as a form, an API, or integration with a 3rd party system, like the one to calculate tax.
- HTTP tests to test APIs described here
- Database test helper functionality described here helps you to do basic things like resetting the DB or seeding it
- Browser tests as described here or here, although browser tests are better to be part of end-to-end tests to provide more value
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Tests\TestCase; class ExampleTest extends TestCase { /** * A basic test example. * * @return void */ public function test_a_basic_request() { $response = $this->get('/'); $response->assertStatus(200); } }
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Tests\TestCase; class ExampleTest extends TestCase { useRefreshDatabase; /** * A basic functional test example. * * @return void */ public function test_basic_example() { $response = $this->get('/'); // ... } }
We will get into more details of both in the next section.
Laravel End-to-End Testing
End-to-end testing is for testing your flows on your website end-to-end the way end-user's would do it.
We won't go into Selenium-based stuff since it is nightmarishly complex, and you can learn about Selenium everywhere.
Laravel Dusk
<?php namespace Tests\Browser; use App\Models\User; use Illuminate\Foundation\Testing\DatabaseMigrations; use Laravel\Dusk\Chrome; use Tests\DuskTestCase; class ExampleTest extends DuskTestCase { use DatabaseMigrations; /** * A basic browser test example. * * @return void */ public function test_basic_example() { $user = User::factory()->create([ 'email' => '[email protected]', ]); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', 'password') ->press('Login') ->assertPathIs('/home'); }); } }
You can refer to buttons via text on it, or Dusk/CSS Selectors described here. Unfortunately, there is if you change your code from a button to a-tag, you need to migrate to using click instead of press. Form interaction relies on the same Dusk Selectors or names of the elements.
You can mock things and it is described here. You can mock functions and programmatic constructs as you'd expect to be able to do for a unit test.
- You'll need a way to run your tests - probably a more powerful CI server
- Dusk doesn't cover a lot of important parts of end-to-end tests like email testing or 2FA logins
- You'll constantly need to battle with ChromeDriver getting out of date with the Chrome you have installed on your machine since Chrome auto-updates
testRigor
testRigor is a declarative way of building tests designed purely for end-to-end tests. It is less applicable for unit/integration testing. However, it is orders of magnitude more powerful for end-to-end tests.
- Run those tests on web and mobile browsers with just a config change
- Support email testing, validation, and manipulation (like clicking a link in the email)
- 2FA-based logins with Gmail, SMS, Email, etc.
You can click on elements with click "Submit"
, enter data with enter "Peter" into "First Name"
and validate with check that page contains "Welcome, Peter!"
login check that URL ends with "/home"
login
is a built-in testRigor function that would log you in regardless of how login is implemented. Or, for the sign-up flow, the test might look like this:click "Sign up" generate unique email and enter it into "Email", then save it as "generatedEmail" generate unique name and enter it into "Name", then save it as "generatedName" enter "PasswordSuperSecure" into "Password" click "Submit" check that email to stored value "generatedEmail" was delivered click "Confirm email" check that page contains "Email was confirmed" check that page contains expression "Hello, ${generatedName}"
check that table at the row containing stored value "myId" and column "Status" contains "Paid"
which would work regardless if the table is rendered as an HTML table or if it is rendered as a div-based table.
As you can see, it is very much declarative and completely abstracted from the code of the application. This might be handy in case you need to approve how things work with a customer or involve other people to build tests for your app.
How to do End-to-end Testing with testRigor
Let us take the example of an e-commerce website that sells plants and other gardening needs. We will create end-to-end test cases in testRigor using plain English test steps.
Step 1: Log in to your testRigor app with your credentials.
Step 2: Set up the test suite for the website testing by providing the information below:
- Test Suite Name: Provide a relevant and self-explanatory name.
- Type of testing: Select from the following options: Desktop Web Testing, Mobile Web Testing, Native and Hybrid Mobile, based on your test requirements.
- URL to run test on: Provide the application URL that you want to test.
- Testing credentials for your web/mobile app to test functionality which requires user to login: You can provide the app’s user login credentials here and need not write them separately in the test steps then. The login functionality will be taken care of automatically using the keyword
login
. - OS and Browser: Choose the OS Browser combination on which you want to run the test cases.
- Number of test cases to generate using AI: If you wish, you can choose to generate test cases based on the App Description text, which works on generative AI.
Step 3: Click Create Test Suite.
On the next screen, you can let AI generate the test case based on the App Description you provided during the Test Suite creation. However, for now, select do not generate any test, since we will write the test steps ourselves.
Step 4: To create a new custom test case yourself, click Add Custom Test Case.
Step 5: Provide the test case Description and start adding the test steps.
For the application under test, i.e., e-commerce website, we will perform below test steps:
- Search for a product
- Add it to the cart
- Verify that the product is present in the cart
Test Case: Search and Add to Cart
Step 1: We will add test steps on the test case editor screen one by one.
testRigor automatically navigates to the website URL you provided during the Test Suite creation. There is no need to use any separate function for it. Here is the website homepage, which we intend to test.
First, we want to search for a product in the search box. Unlike traditional testing tools, you can identify the UI element using the text you see on the screen. You need not use any CSS/XPath identifiers.
click "What are you looking for?"
Step 2: Once the cursor is in the search box, we will type the product name (lily), and press enter to start the search.
type "lily" enter enter
Search lists all products with the “lily” keyword on the webpage.
Step 3: The lily plant we are searching for needs the screen to be scrolled; for that testRigor provides a command. Scroll down until the product is present on the screen:
scroll down until page contains "Zephyranthes Lily, Rain Lily (Red)"
When the product is found on the screen, testRigor stops scrolling.
Step 4: Click on the product name to view the details:
click "Zephyranthes Lily, Rain Lily (Red)"
After the click, the product details are displayed on the screen as below, with the default Quantity as 1.
Step 5: Lets say, we want to change the Quantity to 3, so here we use the testRigor command to select from a list.
select "3" from "Quantity"
click "Add to cart"
The product is successfully added to the cart, and the “Added to your cart:” message is displayed on webpage.
Step 6: To assert that the message is successfully displayed, use a simple assertion command as below:
check that page contains "Added to your cart:"
Step 7: After this check, we will view the contents of the cart by clicking View cart as below:
click "View cart"
Step 8: Now we will again check that the product is present in the cart, under heading “Your cart” using the below assertion. With testRigor, it is really easy to specify the location of an element on the screen.
check that page contains "Zephyranthes Lily, Rain Lily (Red)" under "Your cart"
Complete Test Case
Here is how the complete test case will look in the testRigor app. The test steps are simple in plain English, enabling everyone in your team to write and execute them.
Click Add and Run.
Execution Results
Once the test is executed, you can view the execution details, such as execution status, time spent in execution, screenshots, error messages, logs, video recordings of the test execution, etc. In case of any failure, there are logs and error text that are available easily in a few clicks.
You can also download the complete execution with steps and screenshots in PDF or Word format through the View Execution option.
testRigor’s Capabilities
Apart from the simplistic test case design and execution, there are some advanced features that help you test your application using simple English commands.
- Reusable Rules (Subroutines): You can easily create functions for the test steps that you use repeatedly. You can use the Reusable Rules to create such functions and call them in test cases by simply writing their names. See the example of Reusable Rules.
- Global Variables and Data Sets: You can import data from external files or create your own global variables and data sets in testRigor to use them in data-driven testing.
- 2FA, QR Code, and Captcha Resolution: testRigor easily manages the 2FA, QR Code, and Captcha resolution through its simple English commands.
- Email, Phone Call, and SMS Testing: Use simple English commands to test the email, phone calls, and SMS. These commands are useful for validating 2FA scenarios, with OTPs and authentication codes being sent to email, phone calls, or via phone text.
- File Upload/ Download Testing: Execute the test steps involving file download or file upload without the requirement of any third-party software. You can also validate the contents of the files using testRigor’s simple English commands.
- Database Testing: Execute database queries and validate the results fetched.
testRigor enables you to test web, mobile (hybrid, native), API, and desktop apps with minimum effort and maintenance.
Additional Resources
- Access testRigor documentation to know about more useful capabilities
- Top testRigor’s features
- How to perform end-to-end testing
Achieve More Than 90% Test Automation | |
Step by Step Walkthroughs and Help | |
14 Day Free Trial, Cancel Anytime |