使用Laravel 5测试方法和控制器[phpunit]

时间:2015-03-27 14:40:51

标签: php unit-testing phpunit laravel-5

我想对我的项目进行测试,有人可以告诉我如何编写测试或给我一些好的视频课程来学习测试。

在我的例子中,我要测试这部分:

public function getProjectsForUser(){
        if(Auth::user() -> admin_id == NULL){
            $this->id = Auth::user() -> id;
        }else{
            $this->id = Auth::user() -> admin_id;
        }
        $projects = User::findOrFail(Auth::user() -> id)->projects()->where('admin_id', '=', $this->id)->get();

        $role = User::findOrFail(Auth::user() -> id)->roles;

        $users = User::where('admin_id', '=', $this->id)->lists('name','id');

        return array('projects' => $projects,'users' => $users,'roles' => $role );
}

这是我的模型Project.php

这是我的PorojectController:

public function project(Project $projects){
            $this -> projects = $projects ->getProjectsForUser();
            return view('projects',$this -> projects);
        }

以下是检查用户是否已登录的测试...

public function testHome()
        {
            $this->be(User::find(1));
            $response = $this->call('GET', '/projects');
            //CHECK IF AUTH USER
            $this->assertTrue($response->isOk());

    }

现在我需要检查数组中是否有正确的值,$ project,$ role,$ users。

1 个答案:

答案 0 :(得分:1)

您可以使用assertViewHas()来声明应该传递给视图的值。例如:

public function testHome(){
    $this->be(User::find(1));
    $response = $this->call('GET', '/projects');
    //CHECK IF AUTH USER
    $this->assertTrue($response->isOk());

    $this->assertViewHas('projects', 'expected value for projects');
    $this->assertViewHas('users', 'expected value for users');
    $this->assertViewHas('roles', 'expected value for roles');
}

顺便说一下:如果你没有传递第二个参数,那么该方法只会声明该变量存在但不会比较该值。

要使用不同的语法完成相同的操作,您可以使用assertViewHasAll()并将所有内容作为数组传递:

$this->assertViewHasAll([
    'projects' => 'expected value for projects',
    'users' => 'expected value for users',
    'roles' => 'expected value for roles'
]);