mardi 6 septembre 2016

Phpunit test a method that uses another class which is injected in the constructor

Say in my class's constructor I inject another class. In one of my methods my return depends on that class. How can I test that return?

class MyClass {

    protected $directoryThatIWant;

    public function __construct(
        \AnotherClass $directoryThatIWant
    )
    {
        $this->directoryThatIWant = $directoryThatIWant;
    }

    public function getVarFolderPath()
    {
        return $this->directoryThatIWant->getPath('var');
    }
}

and my test class:

class MyClassTest extends \PHPUnit_Framework_TestCase
{
    const PATH = 'my/path/that/I/want';

    protected $myClass;

    protected function setUp()
    {
        $directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->myClass = new myClass(
            $directoryThatIWantMock
        );
    }

    public function testGetVarFolderPath()
    {
        $this->assertEquals(self::PATH, $this->myClass->getVarFolderPath());
    }
}

A method from a mock object returns null, so i'm unsure how I can ensure that $this->myClass->getVarFolderPath() returns the value that I want.

Thanks!

Aucun commentaire:

Enregistrer un commentaire