phpunitHow to use the willReturnMap method in PHPUnit?
The willReturnMap method in PHPUnit is used to specify a map of arguments to return values when a specific method is called. This is useful for testing methods that take multiple arguments and return different values based on the arguments.
Example
$mock = $this->getMockBuilder(MyClass::class)
->setMethods(['myMethod'])
->getMock();
$mock->expects($this->any())
->method('myMethod')
->willReturnMap([
[1, 2, 3, 'foo'],
[4, 5, 6, 'bar'],
]);
$this->assertEquals('foo', $mock->myMethod(1, 2, 3));
$this->assertEquals('bar', $mock->myMethod(4, 5, 6));
Output example
foo
bar
Code explanation
$mock = $this->getMockBuilder(MyClass::class): This creates a mock object of the classMyClass.->setMethods(['myMethod']): This sets the methods to be mocked. In this case, only the methodmyMethodis mocked.->willReturnMap([[1, 2, 3, 'foo'], [4, 5, 6, 'bar']]): This specifies a map of arguments to return values whenmyMethodis called. In this example, whenmyMethodis called with arguments1, 2, 3, it will returnfoo, and when it is called with arguments4, 5, 6, it will returnbar.$this->assertEquals('foo', $mock->myMethod(1, 2, 3)): This asserts that the return value ofmyMethodwhen called with arguments1, 2, 3isfoo.$this->assertEquals('bar', $mock->myMethod(4, 5, 6)): This asserts that the return value ofmyMethodwhen called with arguments4, 5, 6isbar.
Helpful links
More of Phpunit
- How to show warnings in PHPUnit?
- What are PHPUnit required extensions
- How to stop PHPUnit on failure?
- How to skip a PHPUnit test?
- How to use hooks in PHPUnit?
- How to install PHPUnit with a PHAR file?
- How to order tests with PHPUnit?
- How to install PHPUnit from Packagist?
- How to run tests in parallel with PHPUnit?
- How to disable color output in PHPUnit?
See more codes...