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 run tests in parallel with PHPUnit?
- How to run all PHPUnit tests?
- How to run only certain methods in PHPUnit?
- How to mock a static method with PHPUnit?
- How to mock a query builder with PHPUnit?
- How to launch one test with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to use hooks in PHPUnit?
See more codes...