1

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

Test: 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!

Mock does not work with a generators?

2
  • 1
    until you don't iterate the result of the function, this is not really called Commented May 10, 2016 at 11:15
  • @Matteo thanks a lot! Commented May 10, 2016 at 15:18

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.