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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay