【发布时间】:2014-02-28 05:54:08
【问题描述】:
我有一点问题,下面的代码来自我正在测试的控制器中的一种方法。
场景是,您保存了一条记录,然后您会自动被定向到“查看”该记录。所以我在保存到重定向时传递了项目 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');
【问题讨论】:
-
也许我理解错了,但是如果 $project 不是一个对象,那是否意味着项目创建过程失败并且您不应该重定向到它?我通常在 try 块中创建和重定向,如果创建失败,我会在 catch 块中使用输入和异常重定向回来,以便用户解决问题。
标签: php laravel phpunit mockery