Home > Back-end >  How to use phpunit testing with local api
How to use phpunit testing with local api

Time:04-04

I've got 2 docker containers, one with apiplatform and one with symfony which connecting to this api with docker container name, so my url in browser is different than url that connects containers.

url browser: http://apilocal/  
url container: http://api/

I can't use phpunit test, cause in my controller i use http://api/ and it isnt visible throught browser, so everytime it repsonse 500.

Is there any way to do this properly?

CodePudding user response:

If your API responses with an error 500, you're app is not working propably. It should be possible to use phpunit following the Symfony Testing Guidelines.

In a test case which requests a endpoint, you should not use the whole URL with http://api/endpoint, but only the endpoint without the host part (/endpoint).

Bad way:

$client->request('GET', 'http://docker_container/profile');

Good way:

$client->request('GET', 'h/profile');

To test the connection between to services, it is a good practice to mock the other service as first step, and as a second step, you can use for example contract-testing. https://docs.pact.io/ is a good tool to do that.

The tests should run inside the Docker container(s).

CodePudding user response:

And if you use the public URL does it work ? If so, I'd check if the two containers shares the same network. And if so I'd check the effective URL to be sure there's nothing append to the URL requested using:

$response->getEffectiveUrl();

Otherwise, I'd use the mock handler provided by guzzle to mock the HTTP response.

  • Related