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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With