phpunit mock和php生成器


phpunit mock and php generators

类: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不适用于发电机?

如果你像生成器一样使用它,它就会起作用:

    $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);