Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\ClassMethod\BareCreateMockAssignToDirectUseRector\Fixture;

use PHPUnit\Framework\TestCase;
use Rector\PHPUnit\Tests\CodeQuality\Rector\ClassMethod\BareCreateMockAssignToDirectUseRector\Source\AnotherClass;

final class SkipIfAssert extends TestCase
{
public function test()
{
$someMock = $this->createMock(AnotherClass::class);

$anotherClass = new AnotherClass(1, 2, 3, $someMock);

$this->assertSame($someMock, $anotherClass->getSomeMock());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@

final class AnotherClass
{
public function __construct(...$various)
public function __construct($one, $two, $three, private $someMock)
{

}

public function getSomeMock()
{
return $this->someMock;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PHPUnit\CodeQuality\NodeAnalyser\AssertMethodAnalyzer;
use Rector\PHPUnit\CodeQuality\NodeAnalyser\AssignedMocksCollector;
use Rector\PHPUnit\CodeQuality\NodeFinder\VariableFinder;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
Expand All @@ -35,6 +36,7 @@ public function __construct(
private readonly AssignedMocksCollector $assignedMocksCollector,
private readonly BetterNodeFinder $betterNodeFinder,
private readonly VariableFinder $variableFinder,
private readonly AssertMethodAnalyzer $assertMethodAnalyzer,
) {
}

Expand Down Expand Up @@ -125,6 +127,10 @@ public function refactor(Node $node): ?Node
continue;
}

if ($this->isUsedInAssertCall($node, $variableName)) {
continue;
}

// 1. remove initial assign
$variablesToMethodCalls = [];

Expand Down Expand Up @@ -251,4 +257,34 @@ private function isUsedInClosure(ClassMethod|Foreach_ $stmtsAware, string $varia

return false;
}

private function isUsedInAssertCall(ClassMethod|Foreach_ $stmtsAware, string $variableName): bool
{
/** @var StaticCall[]|MethodCall[] $calls */
$calls = $this->betterNodeFinder->findInstancesOfScoped([$stmtsAware], [MethodCall::class, StaticCall::class]);

$assertCalls = [];
foreach ($calls as $call) {
if (! $this->assertMethodAnalyzer->detectTestCaseCall($call)) {
continue;
}

$assertCalls[] = $call;
}

foreach ($assertCalls as $assertCall) {
foreach ($assertCall->getArgs() as $assertCallArg) {
if (! $assertCallArg->value instanceof Variable) {
continue;
}

if ($this->isName($assertCallArg->value, $variableName)) {
return true;
}

}
}

return false;
}
}