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 show warnings in PHPUnit?
- How to skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to run all PHPUnit tests?
- How to ignore a test in PHPUnit?
- How to mock a static method with PHPUnit?
- How to stop PHPUnit on failure?
- How to install PHPUnit with a PHAR file?
- How to use the PHPUnit Framework TestCase?
See more codes...