I'm writing unit tests for an API built in Laravel. I have a database instance specific for running tests against and have configured the phpunit.xml to tell Laravel to use that db during testing.
However, my issue is when it comes to tests that perform a HTTP request to a route:
$response = $this->json('POST', route('api.login'), [
'email' => '[email protected]',
'password' => 'really.secure.password',
]);
The above request goes via my local network and from the application's point of view this is just another request, it doesn't know this is PHPUnit calling, so the auth token is created in my main database (not the testing database).
Now this feels like a pretty common scenario that I am doing so I'm hoping I've just missed some small tip in all the documentation and tutorials.
One solution which feels a bit hacky is to add some middleware which detects if the user-agent header of the request is set to "PHPUnit" and somehow change the environment and database values via the middleware. That feels a bit dirty so I'm reluctant to do it without first asking the SO community.
Can you suggest an existing technique or more elegant approach?
DB_CONNECTIONand it can only write into the test database, so make sure the phpunit.xml is actually used. How are you running your tests? console? phpstorm?artisan test. I've used dd() to confirm that the env values from myphpunit.xmlare being used and they are in PHPUnit but the controller code triggered by the request still uses the normal .env values.createApplication()in your unit test?$this->app->json()instead of$this->json()?$this->createApplication();in the setUp() method of my test and got exactly the same result. Token created in main database.