Zend Framework 2 is one of the more famous MVC and modular PHP frameworks. One of the components provided by this tool, is ZendTest, a set of tools useful to test the applications designed with this framework.

My experience showed me that the best way to test your applications is to find a good compromise among coverage, simplicity and maintenance capabilities.

So let's consider a simple API call made in ZF2

<?php

namespace API\Controller;

use Zend\Mvc\Controller\AbstractController;
use Zend\View\Model\JsonModel;

class UserController extends AbstractController
{
    public function getList()
    {
        $data = [
	["id" => 1, "email" => "test@ŧest.it",  "name": "Test"],
	["id" => 2, "email" => "paul@ŧest.it",  "name": "Paul"],
	["id" => 3, "email" => "jhonny@ŧest.it",  "name": "Jhonny"],
        ];

        return new JsonModel(array(
            "data" => $data,
        ));
    }

The result has a status code 200 and its content is a Json object with an array of arrays in the data attribute. By way of example, let's suppose the UserController result is a list of user objects fetched from a database populated with objects known to you, as you previously inserted them via fixtures.

You can try to write a very quick test to fix the behavior of your controller:

namespace Api\Controller\UserControllerTest
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase as WebTestController;

class UserControllerTest extends WebTestController
    
    public function testGetUserList()
    {
$this->dispatch("/asset/users", "GET");
$this->assertResponseStatusCode(200);
            $content = json_decode($this->getResponse()->getContent());
$this->assertTrue(array_key_exists("data", $content);
    }
}

This simple test uses the ZendTestPHPUnitControllerAbstractHttpControllerTestCase class, helpful to test your actions: you can start with a basic test, that is you can call a route and verify that the answer status is the one expected. Then you can analyze the result to check if received data are consistent with the expected ones.

This testing type can be written very rapidly, and can be used also in a reverse manner, i.e. starting from the expected answer, you can write an action consistent with it.

Comments

comments powered by Disqus

cloudparty

Follow Us