0

I'm using Laravel, Pest for my tests and Mockery for mocking. I have a simple action that looks like so:

public function handle(): array
{
    $sites = [];

    $envDir = dirname(__FILE__, 3).'/env';
    $envFiles = File::glob($envDir.'/.env.*');

    foreach ($envFiles as $envFile) {
        $basename = basename($envFile);
        $site = str_replace('.env.', '', $basename);
        $dotenv = Dotenv::createArrayBacked(dirname($envFile), $basename)
            ->safeLoad();

        if (! isset($dotenv['APP_URL'])) {
            throw new Exception('Missing APP_URL in ' . $basename);
        }

        $sites[$site] = rtrim($dotenv['APP_URL'], '/');
    }

    return $sites;
}

The code loads several .env.[whatever] files and grabs the APP_URL parameter. It works fine, but I want to write a test.

For the File facade, I simply use File::shouldReceive(), etc, and that works great.

I am now trying to mock the Dotenv requirement. I know that I will have to create it from the container (or inject it), but I'm not sure how to do so using createArrayBacked passing different parameters. Is that even possible?

And once that's setup, I can't figure out how to mock it. If someone sends a specific path and filename to createArrayBacked, then safeLoad() is called, then on the resulting array APP_URL is accessed, I want to provide a specific value based on those original parameters passed to createArrayBacked.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
LeonardChallis
  • 7,759
  • 6
  • 45
  • 76
  • I do not follow what you want, could you add the test and an example please? – matiaslauriti Mar 31 '23 at 10:30
  • I would not mock `DotEnv` but fake a file, so when it is read, it reads the fake data I put, and I expect to get that back, so no need to mock anything. Did you try that? – matiaslauriti Mar 31 '23 at 14:03

0 Answers0