Skip to content

Instantly share code, notes, and snippets.

@doulmi
Created July 11, 2021 14:28
Show Gist options
  • Save doulmi/b8048bde7900099445011f9bc84d9b8c to your computer and use it in GitHub Desktop.
Save doulmi/b8048bde7900099445011f9bc84d9b8c to your computer and use it in GitHub Desktop.
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Tymon\JWTAuth\Facades\JWTAuth;
use ReflectionClass;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
*
* @return mixed Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
/**
* Call protected/private property of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $propertyName Property name to call
* @param mixed $value Value if you want to change it
*
* @return mixed Method return.
*/
public function invokeProperty(&$object, $propertyName, $value = null)
{
$reflection = new ReflectionClass(get_class($object));
$property = $reflection->getProperty($propertyName);
$property->setAccessible(true);
if ($value !== null) {
$property->setValue($object, $value);
}
return $property->getValue($object);
}
/**
* Set the currently logged in user for the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string|null $driver
* @return $this
*/
public function actingAs($user, $driver = null)
{
$token = JWTAuth::fromUser($user);
$this->withHeader('Authorization', "Bearer {$token}");
parent::actingAs($user);
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment