Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to to use PHPUnit for testing API requests and responses using just PHP?

Tags:

phpunit

The responses are in JSON and I am using a custom-built MVC framework which I'm not sure how the request and response process is produced. Service methods are created using the following syntax.

public function getSessionsMethod()
{
    // data auto encoded as JSON
    return array('hello', 'world');
}

A request from JavaScript would look like this /svc/api/getSessions. My initial thought was to simply use a streams approach are there best practices for this form of testing?

public function testCanGetSessionsForAGivenId()
{
    $params = http_build_query(
        array(
            'id' => 3,
        )
    );
    $options = array(
        'http' => array(
            'method'  => 'GET',
            'content' => $params,
            )
        );
    $context  = stream_context_create($options);
    $response = file_get_contents(
        'http://vbates/svc/api/getSessions', false, $context
    );
    $json     = json_decode($response);
    $this->assertEquals(3, $json->response);
}
like image 802
ezraspectre Avatar asked Jan 05 '12 18:01

ezraspectre


1 Answers

This doesn't look like unit testing to me but rather integration testing. You can use PHPUnit to do it, but you should understand the difference first.

There are many components involved in getting the response for a given service method:

  1. The dispatcher: Extracts the parameters from the URL and dispatches to the appropriate service method.
  2. The service method: Does the real work to be tested here.
  3. The JSON encoder: Turns the service method's return value into a JSON response.

You should first test these individually in isolation. Once you've verified that the dispatcher and encoder work for general URLs and return values, there's no point in wasting cycles testing that they work with every service method.

Instead, focus your effort on testing each service method without involving these other components. Your test case should instantiate and call the service methods directly with various inputs and make assertions on their return values. Not only will this require less effort on your part, it will make tracking down problems easier because each failure will be limited to a single component.

like image 134
David Harkness Avatar answered Oct 30 '22 05:10

David Harkness