|
14 | 14 | use PhpParser\Node\Stmt\Class_; |
15 | 15 | use PhpParser\Node\Stmt\ClassMethod; |
16 | 16 | use PHPStan\Reflection\ReflectionProvider; |
| 17 | +use PHPStan\Type\ObjectType; |
17 | 18 | use Rector\Doctrine\NodeAnalyzer\AttributeFinder; |
18 | 19 | use Rector\PhpParser\Node\BetterNodeFinder; |
19 | 20 | use Rector\PHPUnit\Enum\PHPUnitAttribute; |
@@ -86,6 +87,16 @@ public function refactor(Node $node): ?Class_ |
86 | 87 | } |
87 | 88 | } |
88 | 89 |
|
| 90 | + // or find a ->method() calls on a setUp() mocked property |
| 91 | + $hasAnyMethodInSetup = $this->isMissingExpectsOnMockObjectMethodCallInSetUp($node); |
| 92 | + if ($hasAnyMethodInSetup && $testMethodCount > 1) { |
| 93 | + $node->attrGroups[] = new AttributeGroup([ |
| 94 | + new Attribute(new FullyQualified(PHPUnitAttribute::ALLOW_MOCK_OBJECTS_WITHOUT_EXPECTATIONS)), |
| 95 | + ]); |
| 96 | + |
| 97 | + return $node; |
| 98 | + } |
| 99 | + |
89 | 100 | if (! $this->shouldAddAttribute($missedTestMethodsByMockPropertyName)) { |
90 | 101 | return null; |
91 | 102 | } |
@@ -269,4 +280,31 @@ private function isAtLeastOneMockPropertyMockedOnce(array $usingTestMethodsByMoc |
269 | 280 |
|
270 | 281 | return false; |
271 | 282 | } |
| 283 | + |
| 284 | + private function isMissingExpectsOnMockObjectMethodCallInSetUp(Class_ $class): bool |
| 285 | + { |
| 286 | + $setupClassMethod = $class->getMethod(MethodName::SET_UP); |
| 287 | + if (! $setupClassMethod instanceof ClassMethod) { |
| 288 | + return false; |
| 289 | + } |
| 290 | + |
| 291 | + /** @var MethodCall[] $methodCalls */ |
| 292 | + $methodCalls = $this->betterNodeFinder->findInstancesOfScoped( |
| 293 | + (array) $setupClassMethod->stmts, |
| 294 | + MethodCall::class |
| 295 | + ); |
| 296 | + foreach ($methodCalls as $methodCall) { |
| 297 | + if (! $this->isName($methodCall->name, 'method')) { |
| 298 | + continue; |
| 299 | + } |
| 300 | + |
| 301 | + if (! $this->isObjectType($methodCall->var, new ObjectType(PHPUnitClassName::MOCK_OBJECT))) { |
| 302 | + continue; |
| 303 | + } |
| 304 | + |
| 305 | + return true; |
| 306 | + } |
| 307 | + |
| 308 | + return false; |
| 309 | + } |
272 | 310 | } |
0 commit comments