# PHPUnit\Framework\MockObject\RuntimeException：尝试配置模拟类 "App\Service\UserService" 上不存在的方法 "getUser"

- **ID:** `php/phpunit-mock-builder-method-exists`
- **领域:** php
- **类别:** test_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

PHPUnit 的模拟构建器试图配置模拟类上不存在的方法，通常是由于方法名拼写错误或该方法为私有/最终/静态方法。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PHPUnit 10.5 | active | — | — |
| PHPUnit 11.0 | active | — | — |

## 解决方案

1. ```
   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.
   ```
2. ```
   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** — 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. (90% 失败率)
- **Using createMock() instead of getMockBuilder() assuming it's a builder issue** — createMock() also uses the same method existence check internally; the error will still occur if the method does not exist. (85% 失败率)
