user4271704
user4271704

Reputation: 763

Create a test case for curl httprequest

PHPUnit has methods to test databases virtually, but how can I test an HTTP service like curl?

My class method gets a URL and requests parameters to send to server. It receives the answer as json and sends this json to another method to parse and return.

I want to create a PHPUnit test case for this class method. Should I provide a real url to my server? Should the server return a successful/error message to this test case?

Upvotes: 0

Views: 1040

Answers (1)

gontrollez
gontrollez

Reputation: 6538

Instead of having the curl connection inside some methods of your class, wrap the curl call in it's own class, mock it, and have it passed to your class.

This way you can test the happy path by having the mock returns the real json, and also simulate curl errors (make the mock behaves like the real curl library).

Same applies for the parsing part. If you move the parsing code to it's own class and have it injected to the "main" class, then you'll be able to mock it, and simulate parsing errors.

For unit testing you should never do real network calls.

Upvotes: 1

Related Questions