PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount any,什么时候用?

标签 php testing phpunit

刚找到PHPUnit_Framework_TestCase::any .

Returns a matcher that matches when the method it is evaluated for is executed zero or more times.

据我所知,方法总是被“零次或多次”调用,我从未调用过方法 -1 次或更少次。所以这个匹配器应该总是匹配的。为什么它存在以及何时使用它?

最佳答案

这是一个小代码示例,显示了方法 ::method()

class SomeClass
{
    public function method(){
        // smth is being done here;
    }
}

class SomeClassTest extends PHPUnit_Framework_TestCase
{
    private $mock;

    public function setUp(){
        $this->mock = $this->getMockBuilder('SomeClass')
                           ->getMock();
    }

    /**
     * @test
     */
    public function canStub(){
        $this->mock->expects($this->any())
                   ->method('method')
                   ->willReturn(true);
        $this->assertTrue($this->mock->method());
    }

    /**
     * @test
     */
    public function willCauseFatalError(){
        $this->mock->method('method')
                   ->willReturn(true);
        $this->assertTrue($this->mock->method());
    }
}

第二次测试将给出 fatal error :调用成员函数 willReturn() on null

更重要的是,如果 SomeClass 除了 method 还有任何其他方法,它们也需要通过 ->expects($this->any( ))...

关于PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount any,什么时候用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42206398/

相关文章:

PHPUnit 监听器已加载但未使用

unit-testing - 如何测试使用 DateTime 获取当前时间的函数?

javascript - 如何获取 data-id 的值并将其放入 twitter Bootstrap 模式中?

php - 删除两个表中的mysql表行

python - 如何在 Python 中测试 random.choice?

testing - 从串行运行 Selenium 测试到并行运行时处理测试数据

php - 为什么这个错误发生在 codeigniter fileupload 上?

javascript - javascript中以下两个有什么区别?

c - 开发中如何编写单元测试?

database - '完整性错误 : column username is not unique' while using Django User model in test