Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a second parameter in a PHPUnit mock object

Tags:

php

phpunit

This is what I have:

$observer = $this->getMock('SomeObserverClass', array('method')); $observer->expects($this->once())          ->method('method')          ->with($this->equalTo($arg1)); 

But the method should take two parameters. I am only testing that the first parameter is being passed correctly (as $arg1).

How do test the second parameter?

like image 351
Joel Avatar asked Nov 22 '08 16:11

Joel


People also ask

How to mock method in PHPUnit?

PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.

What is stub in PHPUnit?

Stub. Stubs are used with query like methods - methods that return things, but it's not important if they're actually called. $stub = $this->createMock(SomeClass::class); $stub->method('getSomething') ->willReturn('foo'); $sut->action($stub);

Should be called exactly 1 times but called 0 times mockery?

Mockery is by default a stubbing library, not a mocking one (which is confusing because of its name). That means that ->shouldReceive(...) by default is "zero or more times". When using ->once(), you say it should be called zero or one time, but not more. This means it'll always pass.


1 Answers

I believe the way to do this is:

$observer->expects($this->once())      ->method('method')      ->with($this->equalTo($arg1),$this->equalTo($arg2)); 

Or

$observer->expects($this->once())      ->method('method')      ->with($arg1, $arg2); 

If you need to perform a different type of assertion on the 2nd arg, you can do that, too:

$observer->expects($this->once())      ->method('method')      ->with($this->equalTo($arg1),$this->stringContains('some_string')); 

If you need to make sure some argument passes multiple assertions, use logicalAnd()

$observer->expects($this->once())      ->method('method')      ->with($this->logicalAnd($this->stringContains('a'), $this->stringContains('b'))); 
like image 112
silfreed Avatar answered Sep 30 '22 17:09

silfreed