phpunitHow to mock a method with different arguments in PHPUnit?
PHPUnit provides a powerful mocking framework that allows us to mock methods with different arguments. We can use the expects() method to specify the arguments that the mocked method should expect. For example:
$mock = $this->getMockBuilder('MyClass')
->setMethods(['myMethod'])
->getMock();
$mock->expects($this->once())
->method('myMethod')
->with($this->equalTo('arg1'), $this->equalTo('arg2'));
This will ensure that the myMethod method is called with the arguments arg1 and arg2.
Code explanation
-
$mock = $this->getMockBuilder('MyClass') ->setMethods(['myMethod']) ->getMock();- This creates a mock object of the classMyClassand sets themyMethodmethod as the only method to be mocked. -
$mock->expects($this->once()) ->method('myMethod') ->with($this->equalTo('arg1'), $this->equalTo('arg2'));- This specifies that themyMethodmethod should be called with the argumentsarg1andarg2.
Helpful links
More of Phpunit
- How to show warnings in PHPUnit?
- How to stop PHPUnit on failure?
- How to mock with PHPUnit?
- How to create a mock object in PHPUnit?
- How to skip a PHPUnit test?
- How to run all PHPUnit tests?
- How to mock a method with PHPUnit?
- What are PHPUnit required extensions
- How to log with PHPUnit?
- How to assert that key exists in an array using PHPUnit?
See more codes...