php
test_error
ai_generated
true
PHPUnit\Framework\MockObject\RuntimeException:尝试配置模拟类 "App\Service\UserService" 上不存在的方法 "getUser"
PHPUnit\Framework\MockObject\RuntimeException: Trying to configure a method "getUser" that does not exist on mock class "App\Service\UserService"
ID: php/phpunit-mock-builder-method-exists
90%修复率
88%置信度
1证据数
2023-11-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| PHPUnit 10.5 | active | — | — | — |
| PHPUnit 11.0 | active | — | — | — |
根因分析
PHPUnit 的模拟构建器试图配置模拟类上不存在的方法,通常是由于方法名拼写错误或该方法为私有/最终/静态方法。
English
PHPUnit's mock builder is trying to configure a method that does not exist on the mocked class, usually due to a typo in the method name or the method being private/final/static.
官方文档
https://docs.phpunit.de/en/10.5/test-doubles.html#test-double-apis解决方案
-
Verify the method name spelling and visibility. Run `php -r "echo (new ReflectionMethod('App\\Service\\UserService', 'getUser'))->isPublic() ? 'public' : 'not public';"` to check if the method exists and is public. -
If the method is static or final, use `onlyMethods()` with the method name, or refactor the class to make the method non-final. Example: `$mock = $this->getMockBuilder(UserService::class)->onlyMethods(['getUser'])->getMock();`
无效尝试
常见但无效的做法:
-
Adding a @runInSeparateProcess annotation to the test method to isolate state
90% 失败
This does not fix the method name mismatch; it just runs the test in a separate process, which may mask the error but the underlying issue persists.
-
Using createMock() instead of getMockBuilder() assuming it's a builder issue
85% 失败
createMock() also uses the same method existence check internally; the error will still occur if the method does not exist.