DEV Community

farhan
farhan

Posted on • Edited on

3 2

PHPUnit mock function with different values

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)
Enter fullscreen mode Exit fullscreen mode

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'],
]);
Enter fullscreen mode Exit fullscreen mode

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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay