Categories: Blog

PHP Automatic Testing Framework | Supported Laravel & Livewire

Share your learning

We are going to discuss PHP testing framework and some of them are fully laravel and livewire supported.

Hey, tech buddies

As we all know, building a large application can be a painful process if we are not able to test each feature of our application as it grows.

Each time we add a new feature to our application we have to test the current feature as well as our old features, to find the broken loops in our code.

This is not an easy task, if we try to do all these things with manual testing.

We can test our application manually as per our application flow but except manual testing we also need to use automatic testing which makes our testing process faster and accurate.

In the upcoming articles we will share the testing process and code and we will use our php shopping cart project for testing.

There are three types of testing

Unit Testing

It is the type of testing in which we test a very small unit of our code like a single method or single class. With unit testing we can ensure that all our methods are performing their action as they are supposed to do.

Functional Testing

When we try to test the whole functionality of a module it is known as functional testing. For example, we have an invoice class and we want  to know the final output of it. Without testing the internal processing of the invoice class, we just want our expected result.

Acceptance Testing

Acceptance testing is a testing method which we can use to test our application in the exact manner the final user intended to use it. We can understand it as the browser based testing and how the application will work for the end user.

PHP is a well known programming language with huge community support. So, there are many PHP testing frameworks available, some of them are listed below.

PHPUnit

PHPUnit is a very popular unit testing framework. It tests a very small portion of our code one by one.
It has prebuilt annotation, assertions, fixtures, stubs and mocking etc. which make our testing code easy and clean.
We can replace our real class objects with test doubles and they will look real, work like real but not actually update our real data. With this way we can test the portion of our code which can mess up with the testing process if used with real objects.
We can use it with almost all kinds of php projects and php frameworks.

Example,

<?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));
    }
}

Codeception

It is another popular PHP testing framework that supports almost all php frameworks. It helps us to automate our testing and lets us sleep well after pushing our code to production.
Codeception provides us all three types of testing like unit, functional and acceptance testing. That means we can ensure that our application will work as expected from all possible aspects.

Although the real human testing is also important but codeception makes our life easier as a developer and tester.

Example,

class SigninCest
{
    public function signInSuccessfully(AcceptanceTester $I)
    {
        $I->amOnPage('/login');
        $I->fillField('Username','davert');
        $I->fillField('Password','qwerty');
        $I->click('Login');
        $I->see('Hello, davert');
    }
}

PESTPHP

PEST is a php testing framework powered by PHPUnit. It provides an elegant, clean and easy to understand testing approach.

You can use your PHPUnit test classes with pest because it is created based on the PHPUnit testing. It provides easy debugging, traces and error location which help us to debug faster, fix sooner.

The best part of PESTPHP is that if you are a Laravel and Livewire fan, it supports both very well. They have even provided lots of Laravel examples in their documentation. We can test our livewire component with PestPhp by using livewire plugin pest-plugin-livewire. 

Example,

test('asserts true is true', function () {
    $this->assertTrue(true);
 
    expect(true)->toBeTrue();
});

StoryPlayer

StoryPlayer is an open-source PHP testing framework. It is a very interesting testing framework because it works with user stories.

Now, what is the user story?

User story contains a simple action and the user is able to perform that. Like, loggedIn users can see their activities on the application.

So, here the action is “see the activities” and the user must be loggedIn. By this way we can create the long lived test cases.

Example,

$story->addAction(function() {
    # login as a subscription user
    usingBrowser()->gotoPage('/login');
    usingForm('login_form')->fillOutFields(
        [
            'username' => 'subscription user',
            'password' => 'my password'
        ]
    );
    usingBrowser()->click()->buttonWithText('Login');

    # click on 'My Account'
    usingBrowser()->click()->linkWithText('My Account');

    # click on 'Invoices'
    usingBrowser()->click()->linkWithText('Invoices');
});

Selenium

Selenium provides support to a wide variety of programming languages. So, we need to install the library with which language we need to go.

It also provides us with web drivers to automate our browser testing. Like GeckoDriver for firefox. We can install these web drivers as per our browser testing requirements.

Selenium documentation has guidelines and recommendations which help us to define our best practice as per our work environment and requirements.

Example,

const {Builder, By, Key, until} = require('selenium-webdriver');

(async function example() {
    let driver = await new Builder().forBrowser('firefox').build();
    try {
        // Navigate to Url
        await driver.get('https://www.google.com');

        // Enter text "cheese" and perform keyboard action "Enter"
        await driver.findElement(By.name('q')).sendKeys('cheese', Key.ENTER);

        let firstResult = await driver.wait(until.elementLocated(By.css('h3')), 10000);

        console.log(await firstResult.getAttribute('textContent'));
    }
    finally{
        await driver.quit();
    }
})();

Behat

Behat is a BDD (Behaviour Driven Development) based testing framework. It enables us to write the test in the user readable format.

With Behat we can simply define the “feature, scenario” in which we use “given, when and then” to complete the process.

Example,

Feature: login
User will fill the credentials
Click on the login button
Redirect to the dashboard

Scenario:
Given login form
When user fill the form
And Click on the login button
Then Validate the credentials
And redirect to the dashboard

It’s amazing, easy to read and use. After this we need to write the testing code to automate this process.

PHPSpec

PHPSpec helps us to write better and cleaner code because it is a BDD (Behaviour driven development) based testing framework.

With this framework we write our tests first and then write the code to satisfy our test cases. At the end refactor the code to complete the feature.

It was inspired by the Ruby testing framework RSpec.

Example,

<?php

namespace spec;

use PhpSpec\ObjectBehavior;

class MarkdownSpec extends ObjectBehavior
{
    function it_converts_plain_text_to_html_paragraphs()
    {
        $this->toHtml("Hi, there")->shouldReturn("<p>Hi, there</p>");
    }
}

Peridot

If you are looking for a lightweight testing framework which allows us to extend its features by adding plugins as per requirements then Peridot is that one.

Peridot is an event driven testing framework so, it allows us to use required plugins, extensions and test helpers etc. along with our main framework.

It uses a describe-it syntax that makes our test cases easy and more readable.

Example,

describe('ArrayObject', function() {
    beforeEach(function() {
        $this->arrayObject = new ArrayObject(['one', 'two', 'three']);
    });

    describe('->count()', function() {
        it('should return the number of items', function() {
            $count = $this->arrayObject->count();
            assert($count === 3, 'expected 3');
        });
    });
});

Kahlan

It is a unit and BDD (Behaviour driven development) testing framework. Kahlan has its own reporters, exporters with a very customizable workflow. We can set stubs to our classes directly which help us to mock our objects and test their functionalities.

It has describe-it syntax similar to modern BDD testing frameworks.

Example,

describe("Setup and Teardown", function() {
    beforeEach(function() {
        $this->foo = 1;
    });

    describe("Nested level", function() {
        beforeEach(function() {
            $this->foo++;
        });

        it("expects that the foo variable is equal to 2", function() {
            expect($this->foo)->toBe(2);
        });
    });
});

There are lots of other PHP testing frameworks also available which we can use.

Please, Comment me if I have missed your favorite PHP testing framework. 

See you in the next article.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago