Skip to content

Instantly share code, notes, and snippets.

@mtovmassian
Last active October 17, 2022 09:54
Show Gist options
  • Save mtovmassian/91c47ca977995b003a4393f15f120048 to your computer and use it in GitHub Desktop.
Save mtovmassian/91c47ca977995b003a4393f15f120048 to your computer and use it in GitHub Desktop.
Helpers for PHP unit testing
<?php
namespace Tests;
use PHPUnit\Framework\TestCase;
class TestUtils
{
public static function invokePrivateMethod(object $object, string $methodName): callable
{
$reflection = new \ReflectionClass($object);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
$invoke = function (...$params) use ($object, $method) {
return $method->invokeArgs($object, $params);
};
return $invoke;
}
public static function setPrivateProperty(object $object, string $propertyName, $value): object
{
$reflection = new \ReflectionClass($object);
$property = $reflection->getProperty($propertyName);
$property->setAccessible(true);
$property->setValue($object, $value);
return $object;
}
public static function getPrivateProperty(object $object, string $propertyName)
{
$reflection = new \ReflectionClass($object);
$property = $reflection->getProperty($propertyName);
$property->setAccessible(true);
return $property->getValue($object);
}
public static function markAsNonStrictUnitTest(TestCase $testClass)
{
if (self::isStrictUnitTestModeActive($testClass)) {
return $testClass->markTestSkipped('Non strict unit test.');
}
}
private static function isStrictUnitTestModeActive(TestCase $testClass): bool
{
if ((isset($testClass->strictUnitTestModeActive))) {
return (bool) $testClass->strictUnitTestModeActive;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment