He escrito un servicio para obtener el token JWT y almacenarlo en caché durante 59 minutos. Estoy escribiendo ahora una prueba para este servicio. En mi AuthService tengo 2 métodos:
public function getToken(): string { $token = $this->cache->getItem('access_token'); // Czy jest token w cache if ($token->isHit()) { return $token->get(); } else { $newToken = $this->getNewToken(); $this->saveTokenInCache($newToken); return $newToken; } } private function saveTokenInCache($tokenToSave): void { $savedToken = $this->cache->getItem('access_token'); $savedToken->set($tokenToSave); $savedToken->expiresAfter(3540); $this->cache->save($savedToken); }y tengo una prueba:
/** * @test */ public function new_token_should_be_fetched_after_expiration() { $this->msGraphAuthService->expects($this->exactly(2)) ->method('getNewToken'); // getToken $this->msGraphAuthService->getToken(); // change time $date = new DateTime(); $date->modify('3541 seconds'); $this->msGraphAuthService->getToken(); } Para Cache estoy usando FileSystemAdapter .
La función de configuración con el método simulado de getNewToken es:
protected function setUp(): void { $kernel = self::bootKernel(); $this->cacheService = new FilesystemAdapter(); $this->serializer = $kernel->getContainer()->get('serializer'); $this->logger = $this->createMock(Logger::class); $this->msGraphAuthService =$this>getMockBuilder(MicrosoftGraphAuthService::class) ->onlyMethods(['getNewToken']) ->setConstructorArgs([$this->logger, "", "", "", ""]) ->getMock(); $this->msGraphAuthService ->method('getNewToken') ->willReturn('{"token_type":"Bearer","expires_in":3599,"ext_expires_in":3599,"access_token":"eyJ..."}'); }Mi objetivo exacto en la prueba new_token_should_be_fetched_after_expiration es verificar si el método getNewToken se ha invocado exactamente 2 veces, pero ¿cómo podría adelantar el tiempo 59 minutos más tarde que ahora?
Intenté hacer algo como:
$date = new DateTime(); $date->modify('3541 seconds');pero no funciona.
Estaría agradecido por la ayuda.
Parece que el tiempo es una dependencia oculta de getNewToken() .
Haz que la dependencia sea más visible. Por ejemplo, ya sea $_SERVER['REQUEST_TIME'] o un parámetro $date más dedicado que lo tenga por defecto (o lo que sea que tengas en la implementación):
... $date = new DateTime(); $token = $this->getNewToken($date); ...Luego puede crear fácilmente tokens que caducan pronto, ya han caducado y/o también puede eliminar la dependencia oculta del tiempo en la rutina de verificación.
Afortunadamente he encontrado solución:
/** * @test * */ public function new_token_should_be_fetched_again_after_expiration() { ClockMock::register(CacheItem::class); ClockMock::withClockMock(microtime(true) - 3600 * 24); // should be invoked exactly 2 times $this->msGraphAuthService->expects($this->exactly(2)) ->method('getNewToken'); // getToken $this->msGraphAuthService->getToken(); $this->msGraphAuthService->getToken(); }Líneas:
ClockMock::register(CacheItem::class); ClockMock::withClockMock(microtime(true) - 3600 * 24);porque la clase CacheItem invocará métodos falsos de ClockMock . En la segunda línea configuré la hora actual hace 24 horas. Provoca que el token caduque inmediatamente.