phpunit
phpunit copied to clipboard
"Class does not exist" warning when MockBuilder::addMethods() used
Q | A |
---|---|
PHPUnit version | 8.5.0 |
PHP version | 7.2.24 |
Installation Method | Composer |
This issue is related to the MockBuilder::setMethods()
method being deprecated, and replaced with addMethods()
and onlyMethods()
(detailed in issue 3911).
I currently have this code for creating a mock "PaymentGateway" object with a stubbed "charge" method, and it works:
$gateway = $this->getMockBuilder('PaymentGateway')
->setMethods(['charge'])
->getMock();
However, with setMethods
being deprecated, I've tried to replace it with addMethods
:
$gateway = $this->getMockBuilder('PaymentGateway')
->addMethods(['charge'])
->getMock();
However this gives me a Class PaymentGateway does not exist warning.
Does the class actually need to exist before we can mock it? Or am I misunderstanding how addMethods
works?
Thank you for your report.
Please provide a minimal, self-contained, reproducing test case that shows the problem you are reporting.
Without such a minimal, self-contained, reproducing test case I will not be able to investigate this issue.
<?php
class ExampleTest extends PHPUnit\Framework\TestCase
{
public function testFails()
{
$mock = $this->getMockBuilder('Example')
->addMethods(['test'])
->getMock();
$mock->method('test')
->willReturn(true);
$this->assertTrue($mock->test());
}
}
This results in the following:
1) ExampleTest::testFails Class Example does not exist
It works if setMethods()
is used instead of addMethods()
.
I would love to see a fix for this.
Something new to this (happens to me too under PHP v8.1.13 and PHPUnit v9.5.26) ?
And ...happy holidays everyone :-)
Any updates on this? Getting the same warning using PHP 8.0.23 and PHPUnit 8.5.28.
getMockBuilder()
will be soft-deprecated (@deprecated
annotation) in PHPUnit 10.1, deprecated (triggering a deprecation warning) in PHPUnit 11, and removed in PHPUnit 12. Therefore no changes should be made to it anymore.
Encountered the same issue using PHPUnit 10.0.15. Is there any way to create a mock object for the class that does not exist yet? Or should we just wait for PHPUnit 10.1 release? What will be a replacement for the getMockBuilder() then?
getMockBuilder()
will be soft-deprecated (@deprecated
annotation) in PHPUnit 10.1, deprecated (triggering a deprecation warning) in PHPUnit 11, and removed in PHPUnit 12. Therefore no changes should be made to it anymore.
I use PHPUnit 10.4.2 and I've got an error: Class "PaymentGateway" does not exist. So, if any way to mock the class that doesn't exist yet?
I know this is a old thread, but with the latest version of PHPUnit (11), it seems there is still no way to mock a class that doesn't exist yet. Is this just not possible?