Answer the question
In order to leave comments, you need to log in
PHPUNIT: How to return different values in mock method?
The official documentation specifies the following option:
$stub = $this->createMock(SomeClass::class);
// Настроить заглушку.
$stub->method('doSomething')
->will($this->onConsecutiveCalls(2, 3, 5, 7));
// Вызов $stub->doSomething() вернёт разное значение каждый раз
$this->assertSame(2, $stub->doSomething());
$this->assertSame(3, $stub->doSomething());
$this->assertSame(5, $stub->doSomething());
$mock->method('handle')->willReturn($this->onConsecutiveCalls($response1, $response2));
ERROR: Method handle may not return value of type PHPUnit\Framework\MockObject\Stub\ConsecutiveCalls, its
return declaration is ": ...\ResponseInterface"
Answer the question
In order to leave comments, you need to log in
This is exactly how it works:
$this->anyMock
->expects($this->exactly(4))
->method('doSomething')
->withConsecutive(...$args)
->willReturnOnConsecutiveCalls(...$results)
expects($this->exactly(N))
You can also return willReturnCallback(function(){
$arguments = func_get_args(); // get the function arguments and do something with them
})
As a rule, you can set the behavior of the function like this
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question