phprestphpunitslim

How do I write unit tests for a REST API built in Slim Framework?


I have an API built in Slim like this:

    $app->group('/'.$endpoint, function () use ($app, $endpoint) {

        $handler = Api\Rest\Handlers\Factory::load($endpoint);

        if (is_null($handler)) {
            throw new \Exception('No REST handler found for '.$endpoint);
        }

        $app->get('(/:id)', function ($id) use ($app, $handler) {
            echo json_encode($handler->get($id));
        });

        $app->post('', function () use ($app, $handler) {
            echo json_encode($handler->post($app->request->post()));
        });

        $app->put(':id', function ($id) use ($app, $handler) {
            echo json_encode($handler->put($id, $app->request->put()));
        });

        $app->delete(':id', function ($id) use ($app, $handler) {
            echo json_encode($handler->delete($id));
        });

    });

$endpoint is a string, for example 'user';

How do I go about writing unit tests for it?

Ideally;

class RestUserTest extends PHPUnitFrameworkTestCase 
{
    public function testGet() 
    {
        $slim = ''; // my slim app
        // set route 'api/user/1' with method GET
        // invoke slim
        // ensure that what we expected to happen did
    }
}

(The REST handler class would make it trivial to mock the results that would ordinarily be backed by a DB.)

It's the nitty gritty of how to spoof the request into Slim that I don't know how to do.


Solution

  • You can have a try with this guidelines. It may help you. I tried it for one of my slim project.

    Let me know if that helps.

    Codes

    <?php
    
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use Slim\Environment;
    
    
    class RoutesTest extends PHPUnit_Framework_TestCase
    {
    
        public function request($method, $path, $options = array())
        {
            // Capture STDOUT
            ob_start();
    
            // Prepare a mock environment
            Environment::mock(array_merge(array(
                'REQUEST_METHOD' => $method,
                'PATH_INFO' => $path,
                'SERVER_NAME' => 'slim-test.dev',
            ), $options));
    
            $app = new \Slim\Slim();
            $this->app = $app;
            $this->request = $app->request();
            $this->response = $app->response();
    
            // Return STDOUT
            return ob_get_clean();
        }
    
        public function get($path, $options = array())
        {
            $this->request('GET', $path, $options);
        }
    
        public function testIndex()
           {
             $this->get('/');
             $this->assertEquals('200', $this->response->status());
           }
    }
    

    full code hosted in Gist . see this