【问题标题】:phpunit mock and php generatorsphpunit mock 和 php 生成器
【发布时间】:2016-05-09 14:12:58
【问题描述】:

班级:https://github.com/Keanor/generatortest/blob/master/src/SomeClass.php

测试:https://github.com/Keanor/generatortest/blob/master/tests/SomeClassTest.php

输出:

keanor@keanor-pc ~/www/generatortest $ ./vendor/bin/phpunit 
PHPUnit 5.3.2 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)class Generator#23 (0) {
}


Time: 31 ms, Memory: 3.75Mb

There was 1 failure:

1) AppTest\SomeClassTest::testMethod2
Expectation failed for method name is equal to <string:method1> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

如果将“yield”替换为“return”测试成功!

Mock 不适用于生成器?

【问题讨论】:

  • 直到你不迭代函数的结果,这才真正被调用
  • @Matteo 非常感谢!

标签: php unit-testing phpunit


【解决方案1】:

如果你像发电机一样使用它就可以工作:

    $mock = $this->getMockBuilder(SomeClass::class)
        ->setMethods(['method1'])
        ->getMock();
    $mock->expects($this->once())
        ->method('method1')
        ->willReturn('');
    foreach ($mock->method2() as $result) {
        var_dump($result);
    }

代替:

    $mock = $this->getMockBuilder(SomeClass::class)
        ->setMethods(['method1'])
        ->getMock();
    $mock->expects($this->once())
        ->method('method1')
        ->willReturn('');
    $result = call_user_func([$mock, 'method2']);
    var_dump($result);

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 2011-11-23
    • 2012-10-22
    • 2014-11-05
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多