Phpunit测试一个方法,该方法使用在构造函数中注入的另一个类

时间:2016-09-06 09:31:52

标签: php unit-testing phpunit

在我班级的构造函数中说我注入了另一个类。在我的一种方法中,我的回归取决于​​那个班级。我该如何测试这种回报?

class MyClass {

    protected $directoryThatIWant;

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

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

和我的测试班:

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());
    }
}

模拟对象中的方法返回null,因此我不确定如何确保$this->myClass->getVarFolderPath()返回我想要的值。

谢谢!

1 个答案:

答案 0 :(得分:1)

您只需要定义模拟对象的行为(如测试双phpunit指南here中所述)。

例如,您可以按如下方式更改设置方法:

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

    $directoryThatIWantMock->expects($this->once())
        ->method('getPath')->with('var')
        ->willReturn('my/path/that/I/want');


    $this->myClass = new myClass(
        $directoryThatIWantMock
    );
}

希望这个帮助

相关问题