PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] Save variable during unit testing Laravel

 January 22, 2022     laravel, php, phpunit, unit-testing     No comments   

Issue

Variable $this->id not visible in another function testExemple

If I pass this variable to a normal function that does not start on a “test” and not to a testing function, everything will work.

Can I fix this somehow?

class LoginTest extends TestCase
{
    protected $id;
    public function testLogin()
    {
        $response = $this->json('post', 'auth/login', 
            ['email' => 'admin@mail.com', 'password' => '12345678'])
            ->assertJsonStructure(['data' => ['id', 'name', 'email']]);

        $response->assertStatus(201);

        $userData = $response->getContent();
        $userData = json_decode($userData, true);
        $this->id = $userData['data']['id'];
    }
    public function testExemple()
    {
        echo($this->id);
    }
}

Solution

Each test runs independently as far as I know, if you want to pass data from one test to another you can use the @depends doc comment like below:

class LoginTest extends TestCase
{
    public function testLogin()
    {
        $response = $this->json('post', 'auth/login', 
            ['email' => 'admin@mail.com', 'password' => '12345678'])
            ->assertJsonStructure(['data' => ['id', 'name', 'email']]);

        $response->assertStatus(201);

        $userData = $response->getContent();
        $userData = json_decode($userData, true);
        return $userData['data']['id']; //Return this for the dependent tests
    }

    /**
      * @depends testLogin
      */
    public function testExample($id)
    {
        echo($id);
    }
}

However the problem you might encounter is that while the $id has a value the user is not actually logged in during this test because everything else (e.g. session) will be wiped clean.

To ensure the user is logged in then you will need to mock user login like below:

    public function testExample()
    {
        $this->actingAs(User::where('email', 'admin@mail.com')->first()); //User now logged in
        echo(\Auth::id());
    }

This ensures the user is logged in and also decouples tests.



Answered By - apokryfos
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing