Reputation: 3827
Is there a way to assert mocked class method string parameter for multiple matches?
$this->getMock()
->expects($this->any())
->method('setString')
->with($this->stringContains('word3'))
->will($this->returnSelf());
This example will pass for ->setString('word1 word2 word3 word4')
What I need to do is match if setString() is called with parameter containing 'word1' AND 'word3'
But
$this->getMock()
->expects($this->any())
->method('setString')
->with(
$this->stringContains('word1'),
$this->stringContains('word3')
)
->will($this->returnSelf());
this implementation is checking for 2 parameters for setString() and this is not what I have intended to check.
Ideas? using $this->callback() ? Is there some better suited PHPUnit assertions for this?
Upvotes: 5
Views: 1608
Reputation: 118
I know this answer is quite late, but I had the same problem and found a solution that seems to be a little bit smarter... :)
Try this: (untested for your case)
$this->getMock()
->expects($this->any())
->method('setString')
->with($this->logicalAnd(
$this->stringContains('word1'),
$this->stringContains('word3')
))
->will($this->returnSelf());
Upvotes: 8
Reputation: 662
I guess this will do what you're looking for:
$this->getMock()
->expects($this->any())
->method('setString')
->with(
$this->callback(
function($parameter) {
$searchWords = array('word1', 'word3');
$matches = 0;
foreach ($searchWords as $word) {
if (strpos($parameter, $word) !== false) {
$matches++;
}
}
if ($matches == count($searchWords)) {
return true;
} else {
return false;
}
}
))
->will($this->returnSelf());
The callback function checks if both values from $searchWords array are part of the first parameter that is passed to setString() method.
Upvotes: 2