<?phpusePsr\Http\Message\ResponseInterfaceasResponse;usePsr\Http\Message\ServerRequestInterfaceasRequest;useSlim\Factory\AppFactory;require__DIR__.'/../vendor/autoload.php';$app=AppFactory::create();$app->get('/hello/{name}',function(Request$request,Response$response,array$args){$name=$args['name'];$response->getBody()->write("Hello, $name");return$response;});$app->get('/api/v1/users',function(Request$request,Response$response){$data=[['name'=>'Bob','age'=>40]];$payload=json_encode($data);$response->getBody()->write($payload);return$response->withHeader('Content-Type','application/json');});// Do not run the app here
// $app->run();
functiongetApplication(){global$app;return$app;}
Create test file tests/HomeTest.php:
<?phpnamespaceTests;useNyholm\Psr7\Uri;usePHPUnit\Framework\TestCase;useSlim\Factory\ServerRequestCreatorFactory;classHomeTestextendsTestCase{publicfunctiontestHello(){$name='Bob';$serverRequestCreator=ServerRequestCreatorFactory::create();$request=$serverRequestCreator->createServerRequestFromGlobals();$uri=newUri();$request=$request->withUri($uri->withPath("/hello/{$name}"));$response=getApplication()->handle($request);$responseContent=(string)$response->getBody();$this->assertEquals("Hello, {$name}",$responseContent);}publicfunctiontestJsonApi(){$serverRequestCreator=ServerRequestCreatorFactory::create();$request=$serverRequestCreator->createServerRequestFromGlobals();// Uri and Request objects are immutable - create new instances
$uri=newUri();$request=$request->withUri($uri->withPath('api/v1/users'));// For fake query parameters:
// $request = $request->withQueryParams([]);
$response=getApplication()->handle($request);$responseContent=(string)$response->getBody();$this->assertJson($responseContent);}}
Finally, execute tests with PHPUnit:
$ phpunit
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.
.. 2 / 2(100%)
Time: 45 ms, Memory: 4.00 MB
OK (2 tests, 2 assertions)