简体   繁体   English

phpunit模拟和php生成器

[英]phpunit mock and php generators

Class: https://github.com/Keanor/generatortest/blob/master/src/SomeClass.php 类: https//github.com/Keanor/generatortest/blob/master/src/SomeClass.php

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

Output: 输出:

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.

if "yield" is replaced by "return" test succeeds! 如果将“ yield”替换为“ return”,则测试成功!

Mock does not work with a generators? 模拟不能与发电机一起工作吗?

It works if you use it like a generator: 如果您像生成器一样使用它,它将起作用:

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

instead of: 代替:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM