Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking laravel environment in test

I'm implementing some logic that requires code to behave differently in a production environment.

I want to write a test that asserts this actually happens, but I'm having difficulty mocking the environment.

I've seen it suggested to use putenv('APP_ENV=production'); but it doesn't seem to work.

How can I make the test pass?

use Illuminate\Support\Facades\App;
use Tests\TestCase;

class EnvTest extends TestCase
{
    public function testEnv()
    {
        // This assertion is fine
        $env = App::environment();
        $this->assertEquals('testing', $env);

        putenv('APP_ENV=production');

        // This assertion fails
        $env = App::environment();
        $this->assertEquals('production', $env);
    }
}

Result

Time: 160 ms, Memory: 18.00MB

There was 1 failure:

1) EnvTest::testEnv

Failed asserting that two strings are equal.

--- Expected

+++ Actual

@@ @@

-'production'

+'testing'

like image 490
Daniel Avatar asked Jun 13 '18 18:06

Daniel


2 Answers

I know this question is a year old now, but for those who come looking like I did, this worked for me in 5.8

  public function test_config_env()
  {
    $this->app->detectEnvironment(function() {
      return 'production';
    });
    $this->assertEquals('production', app()->environment()); // pass
  }
like image 146
Ben Davison Avatar answered Nov 15 '22 03:11

Ben Davison


use App;

//...

public function my_awesome_test() 
{
    // Number of times method environment() have to be invoked
    $number_of_calls_to_method = 2

    // Fake, that we have production environment
    App::shouldReceive('environment')
        ->times($number_of_calls_to_method)
        ->andReturn('production');

    // Make here whatever you want in Production environment
}
like image 42
staskrak Avatar answered Nov 15 '22 04:11

staskrak