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 methodmyMethod
is mocked.->willReturnMap([[1, 2, 3, 'foo'], [4, 5, 6, 'bar']])
: This specifies a map of arguments to return values whenmyMethod
is called. In this example, whenmyMethod
is 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 ofmyMethod
when called with arguments1, 2, 3
isfoo
.$this->assertEquals('bar', $mock->myMethod(4, 5, 6))
: This asserts that the return value ofmyMethod
when called with arguments4, 5, 6
isbar
.
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to show warnings in PHPUnit?
- How to mock a method with different arguments in PHPUnit?
- What are PHPUnit required extensions
- How to run PHPUnit in quiet mode?
- How to run tests in parallel with PHPUnit?
- How to mock a property in PHPUnit?
- How to mock a static method with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to mock a query builder with PHPUnit?
See more codes...