Testing the private/protected methods of a PHP Trait

The Trait The Test

Login

Blog History

The Trait

<?php

declare(strict_types=1);

namespace App\Lib\Help\Traits;

trait HelpServiceShellExecTrait
{
    protected function shellExec(string $cmd)
    {
        // redirect stderr so we can see the output
        // if the command fails
        return trim((string) shell_exec(sprintf('%s 2>&1', $cmd)));
    }
}

The Test

<?php

namespace App\Test\TestCase\Lib\Help;

use App\Lib\Help\Traits\HelpServiceShellExecTrait;
use Cake\TestSuite\TestCase;
use ReflectionObject;

class HelpServiceTest extends TestCase
{
    public function testShellExecOnHelpServiceServer()
    {
        $class = new class {
            use HelpServiceShellExecTrait;
        };

        $reflected = new ReflectionObject($class);

        $myMethod = $reflected->getMethod('shellExec');

        $myMethod->setAccessible(true);

        $result = $myMethod->invokeArgs($class, ["echo \"hi\"\n\n"]);

        $this->assertEquals("hi", $result);
    }
}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.