我有一个问题,下面的代码来自我正在测试的控制器中的一个方法。
场景是,您保存了一条记录,并且您将自动定向到“查看”该记录。所以我在保存到重定向时传递了项目ID ...
然而,当运行测试时,我收到'ErrorException:试图获取非对象的属性',如果我直接传入对象的id。因此,我正在通过测试的工作是一个三元条件,看看输出是否是一个对象...肯定有一个更好的方法来做到这一点?
我正在使用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');
答案 0 :(得分:1)
当调用方法create
以正确模拟真实行为时,您必须定义模拟的响应:
$mockProject = new StdClass; // or a new mock object
$mockProject->id = 1;
$this->mock->shouldReceive('create')->once()->andReturn($mockProject);