Last active
January 2, 2022 10:37
-
-
Save BinaryKitten/52ca0b9acaeb29611a9d6282a317d203 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Tests; | |
use App\SomeClass; | |
use App\AnotherClass; | |
use PHPUnit\Framework\TestCase; | |
use Tests\Traits\TestsObjects; | |
class DemoTest extends TestCase | |
{ | |
use TestsObjects; | |
public function testObjectPrivateMethod(): void | |
{ | |
$expected = sha1(random_bytes(11)); | |
$someClass = new SomeClass(); | |
$result = $this->invokeMethod($someClass, 'someMethod', random_int(11, 99)); | |
$this->assertSame($expected, $result); | |
} | |
public function testAnotherClassThatDependsOnThing(): void | |
{ | |
$expected = sha1(random_bytes(11)); | |
$someMethodArg = random_int(11, 99); | |
$this->mockMethod( | |
$mockSomeClass = $this->createMock(SomeClass::class), | |
'someMethod', | |
[$someMethodArg] | |
)->willReturn($expected); | |
$anotherClass = new AnotherClass($mockSomeClass); | |
$result = $anotherClass->anotherMethod($someMethodArg); | |
$this->assertSame($expected, $result); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Tests\Traits; | |
use PHPUnit\Framework\MockObject\Builder\InvocationMocker; | |
use PHPUnit\Framework\MockObject\MockObject; | |
use ReflectionException; | |
use ReflectionMethod; | |
trait TestsObjects | |
{ | |
/** | |
* @param class-string|object $class | |
* @param string $methodName | |
* @param ...$args | |
* @return mixed | |
* @throws ReflectionException | |
*/ | |
private function invokeMethod($class, string $methodName, ...$args) | |
{ | |
$method = new ReflectionMethod($class, $methodName); | |
$method->setAccessible(true); | |
return $method->invokeArgs($class, $args); | |
} | |
private function mockMethod(MockObject $mock, string $methodName, array $args = []): InvocationMocker | |
{ | |
$invoker = $mock | |
->expects($this->atLeastOnce()) | |
->method($methodName); | |
if (!empty($args)) { | |
$invoker->with(...$args); | |
} | |
return $invoker; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment