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 classMyClass
and sets themyMethod
method as the only method to be mocked. -
$mock->expects($this->once()) ->method('myMethod') ->with($this->equalTo('arg1'), $this->equalTo('arg2'));
- This specifies that themyMethod
method should be called with the argumentsarg1
andarg2
.
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to disable deprecation notices in PHPUnit?
- How to show warnings in PHPUnit?
- How to stop PHPUnit on failure?
- How to run all PHPUnit tests?
- What are PHPUnit required extensions
- How to mock a static method with PHPUnit?
- How to mock a query builder with PHPUnit?
- How to run PHPUnit in quiet mode?
- How to run tests in parallel with PHPUnit?
See more codes...