0

我正在使用 Phpunit 在 laravel 中进行单元测试。情况是我必须将模型实例从控制器返回到测试类。在那里我将使用该对象的属性来测试一个断言。我怎样才能做到这一点?

目前我正在将该实例 json 编码到响应中。并以一种有效但丑陋的方式使用它。需要一个更清晰的方法。

这是我的测试课:

/** @test
*/
function authenticated_user_can_create_thread()
{
    //Given an authenticated user

    $this->actingAs(factory('App\User')->create());

    //and a thread

    $thread = factory('App\Thread')->make();

    //when user submits a form to create a thread

    $created_thread = $this->post(route('thread.create'),$thread->toArray());

    //the thread can be seen

    $this->get(route('threads.show',['channel'=>$created_thread->original->channel->slug,'thread'=>$created_thread->original->id]))
        ->assertSee($thread->body);
}

这是控制器方法:

public function store(Request $request)
{
    $thread = Thread::create([
        'user_id'=>auth()->id(),
        'title'=>$request->title,
        'body'=>$request->body,
        'channel_id'=>$request->channel_id,
    ]);

    if(app()->environment() === 'testing')
    {
       return response()->json($thread);   //if request is coming from phpunit/test environment then send back the creted thread object as part of json response
    }

    else 
        return redirect()->route('threads.show',['channel'=>$thread->channel->slug,'thread'=>$thread->id]);
}

正如您在测试类中看到的,我在$created_thread变量中接收到从控制器返回的对象。然而,控制器正在返回一个Illuminate\Foundation\Testing\TestResponse的实例,因此嵌入在此响应中的 THREAD 不容易提取。你可以看到我在做 --> $created_thread-> original ->channel->slug,'thread'=>$created_thread-> original ->id]。但我相信有更好的方法来实现同样的目标。

谁能指导我正确的方向?

4

1 回答 1

0

PHPUnit 是一个单元测试套件,因此得名。根据定义,单元测试是为每个单元编写测试——即每个类、每个方法——尽可能与系统的每个其他部分分开。用户可以使用的每一件事,你都想尝试测试它——除了其他所有东西之外,只有它——按照指定的方式运行。

你的问题是,没有什么可以测试的。您还没有创建任何具有可测试逻辑的方法。测试控制器动作是没有意义的,因为它只能证明控制器正在工作,这是 Laravel 的创建者需要检查的事情。

于 2017-10-25T17:21:47.697 回答