将模型实例从控制器返回到laravel中的测试类

时间:2017-10-25 15:42:23

标签: phpunit laravel-5.4 laravel-testing

我正在使用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->的原始 - >通道 - >蛞蝓,'螺纹' => $ created_thread->的原始 - >编号]。但我确信有更好的方法可以达到同样的目的。

有人可以指导我走向正确的方向吗?

1 个答案:

答案 0 :(得分:0)

  

PHPUnit是一个单元测试套件,因此得名。单元测试是,   定义,为每个单元编写测试 - 即每个类   方法 - 尽可能与每个其他部分分开   系统。用户可以使用的每件事,你想尝试测试它 -   只有它,除了其他一切 - 按照规定运作。

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

相关问题