5

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?

1

2 Answers 2

8

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());
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.