Turn your manual testers into automation experts Request a DemoStart testRigor Free

Symfony Testing

Symfony Testing

It's hard enough to find an error in your code when you're looking for it; it's even harder when you've assumed your code is error-free — Steve McConnell, Author, Code Complete.

Wherever there is code, bugs walk in tandem. It is futile to think any software can be perfect and 100% bug-free. But the bottom line is to reach near perfection by adopting the best test strategies, approaches, and impeccable test planning.

This article will help you keep your Symfony code error-free by diving into the necessary types of testing and tools to complement those types.

What is Symfony?

Symfony is a popular open-source PHP web application framework that follows the model-view-controller (MVC) architectural pattern. It provides a set of decoupled, reusable Symfony components and tools for building robust and scalable web applications. PHP applications like Drupal, Prestashop, and Laravel are built on the Symfony framework. You see here how popular Symfony is.

Symfony's author is Fabien Potencier, with the first stable build released in 2005. Currently, it is managed by the enthusiastic Symfony community. It gets preference over other frameworks because of its flexible, customizable, refined MVC architecture, colossal community, innovation, stability, and Open Source MIT license.

Find the compelling reasons to choose Symfony over other frameworks here.

Testing Types Required for Symfony Applications

Let us focus on what testing types are required to test a Symfony-based application. As per the testing pyramid, we need to perform the below testing types to test a Symfony application ideally:
Software Testing Pyramid
Software Testing Pyramid

The number of test cases decreases as we move up the testing pyramid. Unit tests are more in number, and system/E2E tests are less in number comparatively. However, it is worth noting that the cost, complexity, and time associated with the testing types in the testing pyramid increase as we move upwards.

The following sections discuss the essential testing type and the associated tools for Symfony-based application testing.

Unit Testing

Unit tests verify that the individual unit of an application (component, class, method) works as intended in isolation. They are low-level, smallest, fast, and many compared to integration or E2E tests. Unit tests are primarily performed as white box testing by developers mostly.

PHPUnit integrates seamlessly with Symfony and helps write and execute the unit tests.

PHPUnit

It provides assertions, mocks, and other features for writing effective unit tests. While using PHPUnit for writing unit tests, the test/ directory should replicate the application's directory. The filename should be in the format <ComponentName>Test.php by convention. You need to install it separately since PHPUnit is a different package. The autoloading feature gets enabled by default which lists all the unit test files in the tests folder.
Let's create a sample class named Employee.php.
namespace AppBundle\Libs; 

class Employee { 
  public function show($name) { 
    return $name. “, Employee Address is generated!”; 
  } 
}
For the above class file, EmployeeTest.php is the unit test script file.
namespace Tests\AppBundle\Libs;
use AppBundle\Libs\Employee;

class EmployeeTest extends \PHPUnit_Framework_TestCase {
  public function testShow() {
    $Empl = new Employee();
    $assign = $Empl->show('Empl1');
    $check = “Empl1 , Employee Address is generated!”;
    $this->assertEquals($check, $assign);
  }
}

Run the unit tests using the bin/phpunit command.

Integration Testing

It tests the integration between two components or services, such as how databases or APIs interact within the application. To perform integration testing, use Symfony Kernel, which fetches services from the dependency injection container. Symfony provides KernelTestCase class for creating and booting the kernel.

The KernelTestCase ensures that the kernel is rebooted for each test so that every test runs independently from the other. It provides tools for booting the Symfony Kernel, simulating requests, and asserting the expected behavior of the application.

See an example of an HTTP API script below:
<?php
namespace App\Tests\Functional\Service;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use App\Service\WeatherApiClient;

class WeatherApiClientTest extends KernelTestCase
{
  public function testGetCurrentWeatherInvokesTheApiAndReturnsTheExpectedResponse()
  {
    self::bootKernel();
    $apiClient = self::$container->get(WeatherApiClient::class);
    $result = $apiClient->getCurrentWeather('New York', 'NY');
    $this->assertArrayHasKey('weather', $result['response']);
    $this->assertGreaterThanOrEqual(1, $result['response']['weather']);
    $this->assertArrayHasKey('main', $result['response']['weather'][0]);
    $this->assertArrayHasKey('description', $result['response']['weather'][0]);
    $this->assertArrayHasKey('main', $result['response']);
    $this->assertArrayHasKey('temp', $result['response']['main']);
    $this->assertArrayHasKey('feels_like', $result['response']['main']);
    $this->assertArrayHasKey('humidity', $result['response']['main']);
    $this->assertArrayHasKey('visibility', $result['response']);
    $this->assertArrayHasKey('wind', $result['response']);
    $this->assertArrayHasKey('speed', $result['response']['wind']);
    $this->assertArrayHasKey('deg', $result['response']['wind']);
  }
}

Testing Database Integration

Symfony allows the creation of an exclusive test database so that there is no miscommunication with other environments. Hence the steps are: create a test database, configure it with the test runner, and then execute integration tests that involve database actions.

See an example of database integration tests below:
public function testAddSavesANewRecordIntoTheDatabase()
{
  $testWeatherQuery1 = WeatherQuery::build('My City 1', 'MY STATE 1');
  $testWeatherQuery2 = WeatherQuery::build('My City 2', 'MY STATE 2');
  
  self::bootKernel();
  $repository = self::$container->get(WeatherQueryRepository::class);
  
  $repository->add($testWeatherQuery1);
  $repository->add($testWeatherQuery2);
  
  $records = $repository->findAll();
  
  $this->assertEquals(2, count($records));
  $this->assertEquals('My City 1', $records[0]->getCity());
  $this->assertEquals('MY STATE 1', $records[0]->getState());
  $this->assertEquals('My City 2', $records[1]->getCity());
  $this->assertEquals('MY STATE 2', $records[1]->getState());
}

System / E2E Testing

End-to-end testing or system testing focuses on testing the complete user flow. Here a tester checks the seamless integration between the Model, View, and Controller from the user's perspective in the context of Symfony.

Symfony provides a built-in testing framework called Symfony Panther that utilizes the WebDriver protocol for E2E testing.

Symfony Panther

Panther is a library used for browser testing and web scraping, which comes as a package during Symfony installation.

Panther implements the browserKit and DomCrawler APIs to simulate a web browser. These APIs help to execute the browser scenarios in PHP implementation or web browser through WebDriver browser automation protocol. Hence, it enables you to write E2E tests that simulate user interactions with your application, including browsing pages, submitting forms, and validating responses.

See a sample Panther script below:
namespace App\Tests;
use Symfony\Component\Panther\PantherTestCase;

class CommentsTest extends PantherTestCase
{
  public function testComments()
  {
    $client = static::createPantherClient();
    $crawler = $client->request('GET', '/news/symfony-live-usa-2023');
    
    
    $client->waitFor('#post-comment'); 
    $form = $crawler->filter('#post-comment')->form(['new-comment'=>'Symfony is cool!']);
    $client->submit($form);
    
    
    $client->waitFor('#comments ol'); 
    
    
    $this->assertSame(self::$baseUri.'/news/symfony-live-usa-2023', 
    $client->getCurrentURL()); 
    $this->assertSame('Symfony is cool!', 
    $crawler->filter('#comments ol li:first-child')->text());
  }
}

Traditional (Legacy) Automation Testing Tools

You may use traditional automation testing tools for testing Symfony-based applications. A plethora of automation testing tools, Selenium-based, are available in the market. They work on CSS or XPath for element identification, which makes the test script unstable. A minute change in the DOM will affect the test script, and rework will fall into the tester's bucket.

Additionally, a sound knowledge of programming language makes traditional automation testing difficult for manual testers and non-technical stakeholders. Read here the 11 reasons not to use Selenium for automation testing.

Behavior-Driven Development

BDD (Behavior-Driven Development) focuses on collaboration between technical and non-technical stakeholders such as developers, testers, business analysts, product managers, sales, marketing, etc. They all can collaborate and develop test scenarios in plain English, which are then further converted into test scripts.

Symfony supports BDD through tools like Behat, which allows you to write human-readable scenarios. Behat tests use Gherkin syntax to provide a higher-level overview of your application's features.

General Steps for Symfony Testing

  • Up: Install the necessary dependencies, such as PHPUnit and Symfony Panther, to set up the test environment.
  • Determine Tests: Find out which test types you need, i.e., unit tests, system tests, integration tests, BDD tests, or a combination of these.
  • Write Tests: Create test scripts based on the test types. For example, unit tests require the focus on testing individual methods or classes in isolation.
  • Run Tests: Symfony provides commands and utilities to execute tests and generate test reports accordingly.
  • Maintain Continuity: Testing is not a one-time process; continuously run tests during development to ensure that new code changes do not introduce bugs. Use CI/CD pipelines to integrate development and test environments and maintain continuous testing.

How is testRigor Different?

testRigor is a next generation no-code automation tool with integrated AI that helps create automated test cases faster, and spend nearly no time on maintenance. Use testRigor's generative AI-based test script generation, where you just need to provide the test case title and the steps will be automatically generated within seconds.

Below are some advantages of testRigor over other tools:

  • Versatile test creation: Select from three convenient ways to create tests - write tests yourself in plain English, use our test recorder, or employ generative AI for test creation.
  • Ultra-stable: testRigor employs no-code test scripts, which eliminates dependencies on any specific programming language. Elements are referenced as they appear on the screen, thereby reducing reliance on implementation details. This greatly simplifies the process of test creation and debugging.
  • Cloud-hosted: Save time, effort, and resources on infrastructure setup. With testRigor, you are ready to start writing test scripts right after signing up, boasting a speed up to 15 times faster compared to other automation tools.
  • Comprehensive testing coverage: testRigor supports all main types of testing and accommodates cross-browser and cross-platform tests. Its built-in integrations with CI/CD, ERP, and test management tools ensure a seamless and efficient testing process.
See a sample test script of testRigor written in plain English below:
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}"

Read about other valuable features of testRigor here.

Conclusion

A Symfony application requires the execution of unit, integration, E2E, system, and BDD testing types individually or as an amalgamation. Apart from the in-built tools Panther and PHPUnit, external automation test tools can be relied upon to speed up the delivery cycle. These automation tools help implement the test dependencies such as test environment setup, test setup, execution, and reporting.

Choice of automation test tool is critical to the success of the testing process. Therefore, assessing the test suite requirements thoroughly and deciding on the testing tool is advisable. Instead of using multiple testing tools and managing them separately, a single tool testRigor can quickly aid the whole testing process or testing types with the least effort and low cost.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.