farhan
Posted on November 21, 2020
When writing unit test, we sometimes mock a function with different
parameter values and expect different return value(s). For example in the popular e-commerce system magento, it's product model class has a getData function. Using this function you can get different attribute(s) of a product.
Function signature
getData($key = '', $index = null)
We wish to get the product color and product size attributes. The code $product->getData('color') should return value "red" and the code $product->getData('size') should return "s". The second parameter $index is null, you can change it to any other value depending on your requirement.
Example mock code
$product = $this->createMock(Product::class);
$product->method('getData')->willReturnMap([
['color', null, 'red'],
['size', null, 's'],
]);
Learning objectives
Test your php classes
Continuous integration
Prerequisites
Experience with the basics of variables, data types, and running php scripts
Experience setting up PHPUnit, ideally with Composer
Article originally published on http://www.rosenborgsolutions.com/articles/phpunit/phpunit-mock-same-function-with-different-parameters
Posted on November 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.