Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit test a class with an expects() method in it

Tags:

php

phpunit

The problem is the dependency that I am mocking has an expects() method. This class is a dependency on the class I am testing.

setUp() method

$this->test = $this->getMockBuilder(Request::class)->disableOriginalConstructor()
        ->getMock();

So when I write my test

$this->test->expects($this->once())->method('otherMethod')
        ->willReturn(0);

This will give an error:

Cannot redeclare Mock_Test_f21c25ee::expects() in ...

How can I solve this?

Edit:

After i tried the suggested solution with the setMethodsExcept() I now have a different error message. I am also using PHPunit 7.5

Declaration of Mock_Test_fa1cb6c5::expects(PHPUnit\Framework\MockObject\Matcher\Invocation $matcher) should be compatible with App\Services\Api\Test::expects()

Note: Forgot to mention i am using Laravel 5.5 which has its own TestBase Class

Edit2: After i tried using the default PHPUnit testcase i still get the same error message as above. (The must be compatible with error)

like image 468
sietse85 Avatar asked Oct 16 '22 07:10

sietse85


1 Answers

You need to use the setMethodsExcept() method to avoid the redeclaration of the excepts method.

Creating the mock this way should work :

$this->request = $this->getMockBuilder(Request::class)
    ->setMethodsExcept(['expects'])
    ->disableOriginalConstructor()
    ->getMock();

Edit: a bit of clarifications :

To test your case I did the following:

class Expecting
{
    public function get()
    {
        return 'my json';
    }

    public function expects()
    {
        return 'who knows what';
    }
}

class ClassA
{
    public function testMe($the_expect_dependency)
    {
        $the_expect_dependency->get();
    }
}

And in my unit test I had pretty much the same declaration you had :

class ClassATest extends \PHPUnit\Framework\TestCase
{
    public function testThatItCanBeMocked()
    {
        $mock = $this->getMockBuilder(Expecting::class)
            ->setMethodsExcept(['expects'])
            ->disableOriginalConstructor()
            ->getMock();

        $mock->expects($this->once())->method('get')
            ->willReturn('my json');

        $my_obj = new ClassA();
        $my_obj->testMe($mock);
    }
}

When removing the setMethodsExcept() call it gives exactly the error you mentioned, not sure what could have went wrong ?

I'm using phpunit version 7.5 btw.

like image 165
mrbm Avatar answered Nov 15 '22 12:11

mrbm