Search code examples
phpunit-testingphpunitsilex

Unit testing anonymous callback routing in silex


I'm approaching 100% code coverage by phpunit unit tests, but the only thing i'm currently not covering is the routing. And i'm unsure as how to test it. Can anyone be of assistance?

I'm using the Silex framework to do my routing in the following manner:

$api->put('/update/{websiteName}/{endpointName}', function($websiteName, $endpointName, Request $request) use ($databaseServiceContainer, $sourceRetrievalService) {
    $controller = new RequestController(
        $databaseServiceContainer, 
        $sourceRetrievalService
    );

    return $controller->update(
        $websiteName, 
        $endpointName, 
        $request
    );
});

Creating the routing themselves is covered, but not the anonymous callback within.

As you can see within this image:

As you can see within this image.

The full code is available at https://github.com/ri0t1985/api-creator


Solution

  • I'm pretty sure this no need to be unit tested. You can cover a router by the functional/acceptance tests.

    But if you really want to cover a router configuration by the unit tests you can use this approach:

    // ...
    
    $path = '/foo';
    
    $app = new Application();
    $app->get($path, function () {
        return 'foo';
    });
    
    $request = Request::create($path, 'GET');
    $response = $app->handle($request);
    
    $this->assertEquals('foo', $response->getContent());
    // ...
    

    Looking for your implementation on github, the dependensies is getting from DI here. This will be hard to support, so it makes sense to think about how to make this class more testable.

    Hope this helps!