This is the second article in the series of Testing Legacy Code. Check out the first part Testing Legacy Code: Echo Output in which I provide information about the origin of these examples.

The second example covers the invocation of static methods. One of the legacy projects I am supporting is making heavily usage of static methods and no unit tests were written before I started on the project. PHPUnit used to support mocking of static methods with the staticExpects() method. With the help of Mockery, mocking static methods is possible.

Be aware that aliasing classes is supported, but not recommended. See Mockery documentation. The prefered way would be to not use static methods.

Function with invokes a static method

<?php

declare(strict_types=1);

namespace RefactoringLegacyCode;

class StaticMethodInvocation
{
    public function getPowerLevel(): string
    {
        $result = Goku::powerLevel();

        return $result > 9000 ? 'It is over 9000!' : 'Suppressed.';
    }
}

Test

<?php

declare(strict_types=1);

namespace RefactoringLegacyCodeTest;

use Mockery;
use PHPUnit\Framework\TestCase;
use RefactoringLegacyCode\StaticMethodInvocation;

class StaticMethodInvocationTest extends TestCase
{
    /**
     * @covers \RefactoringLegacyCode\StaticMethodInvocation::getPowerLevel
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function test_getPowerLevel_under_9000(): void
    {
        Mockery::mock('alias:RefactoringLegacyCode\Goku')
            ->shouldReceive('powerLevel')
            ->andReturn(37);

        self::assertSame(
            'Suppressed.',
            (new StaticMethodInvocation())->getPowerLevel()
        );
    }

    /**
     * @covers \RefactoringLegacyCode\StaticMethodInvocation::getPowerLevel
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function test_getPowerLevel_over_9000(): void
    {
        Mockery::mock('alias:RefactoringLegacyCode\Goku')
            ->shouldReceive('powerLevel')
            ->andReturn(15000);

        $legacyCode = new StaticMethodInvocation();

        self::assertSame(
            'It is over 9000!',
            (new StaticMethodInvocation())->getPowerLevel()
        );
    }
}