【问题标题】:PHPUnit Mock seemingly not calling public functionPHPUnit Mock 似乎没有调用公共函数
【发布时间】:2014-01-03 10:38:30
【问题描述】:

代码:

MyMockClass.php

<?php
class MyMockClass
{
    public function __construct($l)
    {
        // Do nothing with it
    }

    protected function loadData($var)
    {
        // Do something, it doesn't matter what
        return null;
    }

    public function onEvent($key)
    {
        return $this->loadData($key);
    }
}

MockTest.php

<?php
class MockTest extends \PHPUnit_Framework_TestCase
{
    public function testPHPUnitMock()
    {
        $mock = $this->getMockBuilder('MyMockClass')->setConstructorArgs(array(true))->getMock();
        $mock->expects($this->once())->method('loadData')->with('TEST')->will($this >returnValue(true));

        $this->assertEquals(true, $mock->onEvent('TEST'));
    }

}

当我运行这个测试时,它失败了,输出如下:

PHPUnit_Framework_ExpectationFailedException : Failed asserting that null matches expected true.
Expected :true
Actual   :null

我正在尝试执行onEvent,它又会执行一个我已经模拟过的函数,并改变了它的结果。但是onEvent 函数似乎没有被调用。如果我将mail()(或类似的东西)放入onEvent,我将不会收到任何邮件。

【问题讨论】:

    标签: php unit-testing mocking phpunit


    【解决方案1】:

    如果您不告诉模拟生成器您要模拟哪些方法 - 默认情况下,模拟类中的所有方法都将被模拟。

    在您的情况下,当您在测试中调用 onEvent 方法时,实际上您调用了一个模拟方法。

    如果您指定要模拟的方法,则模拟生成器将仅模拟这些方法,并将其余的保留在原始类中。

    所以,尝试以这种方式构建你的模拟:

    public function testPHPUnitMock()
    {
        $mock = $this->getMockBuilder('MyMockClass')
            ->setMethods(array('loadData')) // this line tells mock builder which methods should be mocked
            ->setConstructorArgs(array(true))
            ->getMock();
        $mock->expects($this->once())->method('loadData')->with('TEST')->will($this->returnValue(true));
    
        $this->assertTrue($mock->onEvent('TEST'));
    }
    

    【讨论】:

    • 你不能嘲笑任何方法谢谢$this-&gt;getMockBuilder(MyClass::class)-&gt;onlyMethods([])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多