【问题标题】:Laravel 5.2 PHPUnit assertViewHasAll() FailedLaravel 5.2 PHPUnit assertViewHasAll() 失败
【发布时间】:2017-03-01 12:49:28
【问题描述】:

嗨,我有这个单元测试

public function test_index_coupon(){

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

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

这是我的控制器来列出优惠券索引

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

而且我可以用

成功列出优惠券
@foreach($coupons as $coupon)
.....
@endforeach

在我看来,我是通过浏览器查看的。

但是当我运行phpunit 时,我得到了这个错误

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'); 并得到不同的错误

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

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

更新

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

感谢您的回答和评论。

【问题讨论】:

    标签: laravel-5 phpunit


    【解决方案1】:
    $this->visit('/admin/coupons')
        ->assertResponseOk()
        ->assertViewHas('coupons', $coupons);
    

    OR(如果您计划在assertViewHasAll 中添加更多数据以进行断言)

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

    【讨论】:

    • 更改为->assertViewHas('coupons', $coupons); 并收到此错误1) CouponsTest::test_index_coupon null does not match expected type "object".
    • $coupons从集合转换为数组:$coupons = factory(App\Models\Coupon::class, 5)->create()->toArray();
    • 我收到了这个1) CouponsTest::test_index_coupon null does not match expected type "array". 它显示为空,但数据是用faker 播种的,并通过视图正确加载。
    【解决方案2】:

    Laravel documentation 中可以看到assertViewHasAll 接收一个数组作为参数。

    ->assertViewHasAll(array $bindings);

    你给它一个字符串:

    ->assertViewHasAll('coupons');

    【讨论】:

    • 那么如何按照我的情况进行测试?
    猜你喜欢
    • 2016-12-01
    • 1970-01-01
    • 2014-08-28
    • 2017-03-26
    • 2020-05-02
    • 2017-05-24
    • 2018-10-26
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多