samedi 29 octobre 2016

PHPUnit How to constraint mock stub method input with array subset containing instanceOf?

I want to test pretty specific piece of code, but I can't find a good way to do it. I have such code:

public function foo()
{
    try {
        //...some code
        $this->service->connectUser();
    } catch (\OAuth2Exception $e) {
        $this->logger->error(
            $e->getMessage(),
            ['exception' => $e]
        );
    }
}

And I want to test if the exception was thrown and logged to $this->logger. But I can't find a good way to do it. Here is how I do it currently.

public function testFoo()
{
    $oauthException = new \OAuth2Exception('OAuth2Exception message');

    //This is a $service Mock created with $this->getMockBuilder() in test case injected to AuthManager.
    $this->service->method('connectUser')
        ->will($this->throwException($oauthException));

    //This is a $logger Mock created with $this->getMockBuilder() in test case injected to AuthManager.
    $this->logger->expects($this->once())
        ->method('error')
        ->with(
            $this->isType('string'),
            $this->logicalAnd(
                $this->arrayHasKey('exception'),
                $this->contains($oauthException)
            )
        );

    //AuthManager is the class beeing tested.
    $this->authManager->foo($this->token);
}

This will test if error method was called with certain parameters, but array key 'exception' and exception object can exist in different parts of the array. What I mean is that test will pass for such error method call:

        $this->logger->error(
            $e->getMessage(),
            [
                'exception' => 'someValue',
                'someKey' => $e
            ]
        );

I would like to make sure that error method will always receive such subset ['exception' => $e]. Something like this would be perfect:

     $this->logger->expects($this->once())
        ->method('error')
        ->with(
            $this->isType('string'),
            $this->arrayHasSubset(
                ['exception' => $oauthException)]
            )
        );

Is it possible to achieve with PHPUnit?

Aucun commentaire:

Enregistrer un commentaire