How Do I Set The Working Directory For Phpunit Using The XML File?

- 1 answer

I'm looking through the documentation, but I'm not seeing any option to change the working directory used when running tests.

I'm using PhpUnit as it's included in Laravel. I want to be able to run vendor/bin/phpunit from my project's root directory, and have it run using the /public directory as the working directory.

I tried running ../vendor/bin/phpunit from the /public, but since the phpunit.xml file isn't in the public directory and I don't want to specify my config file path every time, that won't work.

Is there something I can add to my phpunit.xml file to tell it to run tests using the /public directory as the "cwd" (current working directory)?



Based on the feedback I received in the comments and the documentation, I determined the following:

  1. It's probably not possible to change the cwd that phpunit uses by default (well, it's possible in PhpStorm, but not the command line without writing some kind of wrapper script)
  2. Code that depends on being run from a specific directory is not a good idea.

What I had was some code in one of my classes like this:

$var = file_get_contents("../some_file.json");

This works fine -- until you try to add unit tests. The web server runs using the /public directory as the cwd, while phpunit will run using the root directory.

Rather than trying to force phpunit to always use a particular cwd (/public), I decided it's probably best to remove relative paths from the code that rely on a consistent cwd. So the line above becomes:

$var = file_get_contents(base_path("some_file.json"));

I didn't want to change production code that was already working just to get some tests in place, but this change seemed insignificant enough. (and it's an improvement anyway)