我正在使用 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]。但我相信有更好的方法来实现同样的目标。
谁能指导我正确的方向?