Testing 拉威尔测试误差
我刚开始学习如何在Laravel内部进行测试。但是我遇到了一些问题。。 我正在测试我的控制器,想检查视图是否分配了变量 我的控制器代码:Testing 拉威尔测试误差,testing,laravel,controller,tdd,Testing,Laravel,Controller,Tdd,我刚开始学习如何在Laravel内部进行测试。但是我遇到了一些问题。。 我正在测试我的控制器,想检查视图是否分配了变量 我的控制器代码: class PagesController extends \BaseController { protected $post; public function __construct(Post $post) { $this->post = $post; } public function index() {
class PagesController extends \BaseController {
protected $post;
public function __construct(Post $post) {
$this->post = $post;
}
public function index() {
$posts = $this->post->all();
return View::make('hello', ['posts' => $posts]);
}
}
“我的视图”包含一个foreach循环,用于显示所有帖子:
@foreach ($posts as $post)
{{post->id}}
@endforeach
最后但并非最不重要的是我的测试文件:
class PostControllerTest extends TestCase {
public function __construct()
{
// We have no interest in testing Eloquent
$this->mock = Mockery::mock('Eloquent', 'Post');
}
public function tearDown()
{
Mockery::close();
}
public function testIndex() {
$this->mock->shouldReceive('all')->once()->andReturn('foo');
$this->app->instance('Post', $this->mock);
$this->call('GET', '/');
$this->assertViewHas('posts');
}
}
现在问题来了,当我运行“phpunit”时,出现以下错误:
ErrorException:为foreach()提供的参数无效
知道为什么phpunit会返回此错误吗?您也应该模拟视图:
public function testIndex() {
$this->mock->shouldReceive('all')->once()->andReturn('foo');
$this->app->instance('Post', $this->mock);
View::shouldReceive('make')->with('hello', array('posts', 'foo'))->once();
$this->call('GET', '/');
}
你的问题是:
$this->mock->shouldReceive('all')->once()->andReturn('foo');
$this->post->all()。你正在返回一个字符串
$this->mock->shouldReceive('all')->once()->andReturn(array('foo'));
应该注意您所遇到的错误,尽管随后会出现“Getting property of non object”类型的错误
您可以这样做:
$mockPost = new stdClass();
$mockPost->id = 1;
$this->mock->shouldReceive('all')->once()->andReturn(array($mockpost));
这对我不管用。它返回以下错误:ErrorException:尝试获取非objectI的属性已将其修复。忽略原始答案,只需这样做。您是否将模型的模拟切换回代码中的原始内容?i、 它应该回到$this->mock->shouldReceive('all')->once()->andReturn('foo')代码>-不再是数组…?这也不起作用。错误:mockry\Exception\nomatchingexpectionexception:找不到mockry\u 1\u light\u View\u Factory::make(“hello”,array('posts'=>'foo',)的匹配处理程序。方法是意外的,或者其参数与此方法的预期参数列表不匹配是的,我完全按照您在更新的答案中所说的做了。如果我用我的代码用{posts}替换@foreach等,测试就会成功。它和foreach或其他东西有关。谢谢!这是可行的,但只有当我添加{{posts}}时,才会出现错误:数组到字符串的转换。也有办法解决这个问题吗?我使用FactoryMuff创建了一个快速的帖子,比如:$mockPost=FactoryMuff::create('post');然而,当我调用{{$posts}时,这并不能解决问题,但它确实填充了Post的所有其他字段(比如body)。你不能只回显{{posts},因为它是一个数组——你需要循环它并回显单个条目,就像你问题中的代码一样。啊,对不起。。当您执行{{$posts}}时,laravel将数组转换为json,这在我的测试中没有完成。无论如何,谢谢你,我的错在那里;)