donglu6805 2017-11-30 14:42
浏览 55
已采纳

Laravel phpunit assertViewHas与预期的测试数据不匹配

I am writing a test for my search method, but had currently a assertSee and want to change it for a assertViewHas for a better test result. But the data that I get from the search method does not want to match the data I expect.

This is where I set $user:

protected $user;

public function setUp()
{
    parent::setUp();

    $this->seed();

    $this->user = factory(User::class)->create(['role_id' => 3]);
}

This is where I'm making the assertion:

$response = $this->followingRedirects()->actingAs($this->user)->get('/manage/users/search?choices=username&search='.$this->user->username.'');

$response->assertViewIs('manage.users');
$response->assertSuccessful();
$response->assertViewHas('users', $this->user);

And this is the data it will return from the controller:

$result = User::where('username', 'LIKE', '%'. $request->get('search') .'%')
                ->orderBy('username', 'asc')->paginate(20);
return view('manage.users')->with('users', $result);

What am I doing wrong to get the matching data?

  • 写回答

1条回答 默认 最新

  • dqef7931 2017-11-30 16:55
    关注

    You are trying to assert that $this->user matches $users from your controller. But paginate() returns a LengthAwarePaginator instance and $this->user is an instance of User, so they won't match.

    If you want to assert that a given user is contained in the $users variable passed to the view, you could pass a closure to assertViewHas() with the necessary logic.

    Maybe something like this:

    $response->assertViewHas('users', function($users) {
        return $users->contains($this->user);
    });
    

    You can view how assertViewHas() works on the Laravel source code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用