Laravel 5.2 PHPUnit assertViewHasAll()失败 [英] Laravel 5.2 PHPUnit assertViewHasAll() Failed

查看:115
本文介绍了Laravel 5.2 PHPUnit assertViewHasAll()失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个单元测试

public function test_index_coupon(){

    $coupons = factory(App\Models\Coupon::class, 5)->create();      

    $this->visit('/admin/coupons')
    ->assertResponseOk()
    ->assertViewHasAll('coupons');
}

这里是我列出优惠券索引的控制权

Here is my controller to list index of coupons

   public function index()
    {
        $coupons = Coupon::all();   
        return view('backend.admin.coupons.index', compact('coupons'));
    }

我可以使用

@foreach($coupons as $coupon)
.....
@endforeach

在我看来,我是通过浏览器检查它的.

In my view, I check it via browser.

但是当我运行phpunit时,出现此错误

But when I run phpunit I get this error

1) CouponsTest::test_index_coupon
ErrorException: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::assertViewHasAll() must be of the type array, string given, called in /var/www/html/rentcar/tests/admin/CouponsTest.php on line 24 and defined

然后我尝试将测试从->assertViewHasAll('coupons');修改为->assertViewHas('coupons');,但出现不同的错误

Then I try modify my test from ->assertViewHasAll('coupons'); to ->assertViewHas('coupons'); and I get different error

1) CouponsTest::test_index_coupon
Failed asserting that an array has the key 'coupons'.

我的测试代码有什么问题?我只想检查访问admin/coupons优惠券列表是否正确加载.所以我可以确保视图中是否存在$coupons.

Whats wrong with my test code? I just want to check if visit admin/coupons coupons list loaded properly. so I can make sure if $coupons is exists in view.

更新

它与assertViewHas('coupons')一起使用不知道为什么,也许我的整个测试代码有问题,或者可能是因为use WithoutMiddleware

It works with assertViewHas('coupons') don't know why, maybe something wrong with my entire test code or maybe because use WithoutMiddleware

感谢您的回答和评论.

推荐答案

$this->visit('/admin/coupons')
    ->assertResponseOk()
    ->assertViewHas('coupons', $coupons);

OR(如果您计划添加更多数据以在assertViewHasAll中声明)

OR (int case you plan on adding more data to assert in assertViewHasAll)

$this->visit('/admin/coupons')
    ->assertResponseOk()
    ->assertViewHasAll(['coupons' => $coupons]);

这篇关于Laravel 5.2 PHPUnit assertViewHasAll()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆