mercredi 27 janvier 2016

How to mock Auth in a Laravel 5.2 Modl

I'm trying to write some unit tests for a brand new mini app. I usually write functional tests so this is me branching out to try and do it properly with mocking and stubs and all those things that make it just about the code.

The model looks like this :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;

class myModel extends Model
{
    public static function getUser()
    {
        $user = \Auth::user();
        return $user->adldapUser->cn[0];
    }
}

And the test :

class MyModelTest extends TestCase
{

    public function testGetUser()
    {
        $mockResult = new StdClass();
        $mockResult->adldapUser = new stdClass();
        $mockResult->adldapUser->cn=array("test");
        $auth = $this->getMock('Auth');
        $auth
            ->method('user')
            ->will($this->returnValue($mockResult));

        $this->assertEquals('test',\App\MyModel::getUser());
    }
}

But when I run the unit test I get the following error message :

There was 1 error:

1) MyModelTest::testGetUser ErrorException: Trying to get property of non-object

/home/aidan/web/vagrant-web-dev/src/apps/orcid/app/MyModel.php:61 /home/aidan/web/vagrant-web-dev/src/apps/orcid/tests/MyModelTest.php:18

and if I post out $user it's NULL.

What am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire