Generate mocks and stubs with PHPUnit

Very interesting presentation of Juan Treminio about unit tests and PHPUnit: PDF. He explain how to generate mocks and stubs using the MockBuilder:

  • Generate a basic mock, without call setMethods() method:
    * All methods in mocked object are stubs
    * Return null
    * Methods easily overridable

    $payment = $this->getMockBuilder('AuthorizeNetAIM')
                    ->getMock();
  • Pass an empty array
    * Same as if not calling setMethods()
    * All methods in mocked object are stubs
    * Return null
    * Methods easily overridable

    $payment = $this->getMockBuilder('AuthorizeNetAIM')
                    ->setMethods(array())
                    ->getMock();
  • Pass null
    * All methods in mocked object are mocks
    * Run actual code in method
    * Not overridable

    $payment = $this->getMockBuilder('AuthorizeNetAIM')
                    ->setMethods(null)
                    ->getMock();
  • Pass an array with method names
    –Methods identified are stubs
    • Return null
    • Easily overridable
    –Methods *not* identified are mocks
    • Actual code is ran
    • Unable to override

    $payment = $this->getMockBuilder('Payment')
                    ->setMethods(
                        array('authorizeAndCapture',)
                    )
                    ->getMock();

Source – Juan Treminio presentation
Source – Juan Treminio blog

Some useful PHPUnit methods to make testing easier

<?php
 
namespace jtreminio\TestExtensions;
 
/**
 * Some useful methods to make testing with PHPUnit faster and more fun
 *
 * @author Juan Treminio <jtreminio@gmail.com>
 */
abstract class TestExtensions extends \PHPUnit_Framework_TestCase
{
 
    /**
     * Set protected/private attribute of object
     *
     * @param object &$object       Object containing attribute
     * @param string $attributeName Attribute name to change
     * @param string $value         Value to set attribute to
     *
     * @return null
     */
    public function setAttribute(&$object, $attributeName, $value)
    {
        $class = is_object($object) ? get_class($object) : $object;
 
        $reflection = new \ReflectionProperty($class, $attributeName);
        $reflection->setAccessible(true);
        $reflection->setValue($object, $value);
    }
 
    /**
     * Get protected/private attribute of object
     *
     * @param object &$object       Object containing attribute
     * @param string $attributeName Attribute name to fetch
     * @return mixed
     */
    public function getAttribute(&$object, $attributeName)
    {
        $class = is_object($object) ? get_class($object) : $object;
 
        $reflection = new \ReflectionProperty($class, $attributeName);
        $reflection->setAccessible(true);
        return $reflection->getValue($object);
    }
 
    /**
     * Call protected/private method of a class.
     *
     * @param object &$object    Instantiated object that we will run method on.
     * @param string $methodName Method name to call
     * @param array  $parameters Array of parameters to pass into method.
     *
     * @return mixed Method return.
     */
    public function invokeMethod(&$object, $methodName, array $parameters = array())
    {
        $reflection = new \ReflectionClass(get_class($object));
        $method = $reflection->getMethod($methodName);
        $method->setAccessible(true);
 
        return $method->invokeArgs($object, $parameters);
    }
 
}

Source – Github jtreminio

Customize ResultPrinter in PHPUnit

There are one class that prints the results of the tests when you execute PHPUnit with a testsuite.

If you want, you can customize the way that you print it, setting the colors, the characters, the width, …

You have to create a class that extends “PHPUnit_TextUI_ResultPrinter”, and set that class in your phpunit.xml.

< ?xml version="1.0" encoding="UTF-8"?>
 
<phpunit ...
    printerClass = "MyResultPrinter"
    ...
>
 
    <testsuite name="Application">
        ...
    </testsuite>
</phpunit>

Sigue leyendo Customize ResultPrinter in PHPUnit

PHP: close connection and continue the execution

In HTTP/1.1 definition, it exists a header called “Connection” that, if you define “close”, you are sending that the connection will be closed after completion of the response. The client will know that the response is complete if it know the response length.

The next code calculates the response length, and send the two headers needed to close the connection and continue the execution in the PHP script:

<?php
 
startOutputBuffer();
 
echo ('Text the user will see');
 
flushOutputBuffer();
 
sleep(30);
echo('Text user will never see');
 
function startOutputBuffer()
{
    ob_end_clean();
    ignore_user_abort();
    ob_start();
}
 
function flushOutputBuffer()
{
    $size = ob_get_length();
    header("Connection: close");
    header("Content-Length: $size");
 
    ob_end_flush();
    flush();
}