【问题标题】:Phpunit test a method that uses another class which is injected in the constructorPhpunit 测试一个使用另一个类的方法,该类被注入到构造函数中
【发布时间】:2016-09-06 09:31:51
【问题描述】:

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

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() 返回我想要的值。

谢谢!

【问题讨论】:

    标签: php unit-testing phpunit


    【解决方案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
        );
    }
    

    希望有帮助

    【讨论】:

    • 谢谢。我见过 willReturn(...) 的例子,但我很困惑。那没有测试任何东西对吗?我不确定我的方法 getVarFolderPath 是否返回我想要的
    • 模拟对象构造测试该方法将只被调用一次(期望一次)然后您断言您的真实类将正确使用该对象并且您的断言正常。你的测试现在正常吗?或者你有一些错误/错误的期望?
    • 是的,它是这样工作的,但在这里我并没有真正测试$this->directoryThatIWant->getPath('var') 的输出。我正在做这个测试,因为我的托管公司经常更改 var 文件夹的绝对路径,这会导致细微的错误。据我了解,willReturn() 只是硬编码你想要的,不是吗?它并没有真正做到 \AnotherClass 对 getPath 方法所做的事情
    • 哦,当然,被测试的类是MyClass,是一个单元测试。可能您想对所涉及的真实类进行功能测试,而不是模拟它们
    猜你喜欢
    • 2017-02-25
    • 2015-09-04
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多