我有一点问题,下面的代码来自我正在测试的控制器中的一种方法。
场景是,您保存了一条记录,然后您将自动定向到“查看”该记录。所以我在保存到重定向时传递了项目ID......
但是,在运行测试时,如果我直接传入对象的 id,则会收到“ErrorException: Trying to get property of non-object”。所以围绕我做通过测试的工作是一个三元条件,看看输出是否是一个对象......当然必须有更好的方法来做到这一点?
我正在使用 Mockery,并为 Projects 模型创建了一个模拟类/接口,该模型被注入到 Projects 主控制器中。
这是方法:
public function store()
{
// Required to use Laravels 'Input' class to catch the form data
// This is because the mock tests don't pick up ordinary $_POST
$project = $this->project->create(Input::only('projects'));
if (count(Input::only('contributers')['contributers']) > 0) {
$output = Contributer::insert(Input::only('contributers')['contributers']);
}
// Checking whether the output is an object, as tests fail as the object isn't instatiated
// through the mock within the tests
return Redirect::route('projects.show', (is_object($project)?$project->id:null))
->with('fash', 'New project has been created');
}
这是测试重定向路由的测试。
Input::replace($input = ['title' => 'Foo Title']);
$this->mock->shouldReceive('create')->once();
$this->call('POST', 'projects');
$this->assertRedirectedToRoute('projects.show');
$this->assertSessionHas('flash');