Any way to use PHPUnit to test API requests and responses using only PHP?

The answers are in JSON, and I'm using a custom MVC environment, and I'm not sure how the request and response process is done. Service methods are created using the following syntax.

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

A JavaScript request will look like this: /svc/api/getSessions . My initial thought was to just use the threading approach, are there any better methods 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); } 
+6
source share
1 answer

This is not like unit testing , but rather integration testing . You can use PHPUnit to do this, but first you need to understand the difference.

There are many components to receiving a response for a given service method:

  • Dispatcher: Retrieves parameters from a URL and sends the appropriate service method.
  • Service Method: The real work is tested here.
  • JSON encoder: returns the return value of a service method in a JSON response.

You must first test them separately. After you have confirmed that the dispatcher and the encoder work with common URLs and return values, it makes no sense to spend test cycles on the fact that they work with each service method.

Instead, focus on testing each service method without involving these other components. Your test case should create an instance and call service methods directly with various inputs and make statements about their return values. This will not only require less effort on your part, but will also make it easier to track problems, since each failure will be limited to one component.

+9
source

Source: https://habr.com/ru/post/905226/


All Articles