如何使用Laravel和Mockery测试商店功能

时间:2018-05-26 11:49:20

标签: laravel laravel-5 phpunit mockery

我想使用PHPUnit和Mockery在Laravel 5.6中测试存储库模式。

这是我的代码:

    // PackageControllerTest.php
    ...
    public function index()
    {
        $packages = $this->package->getAllPackages();

        return view('package.index', compact('packages'));
    }

    public function update($package_id)
    {
        $package = $this->package->updatePackage($package_id);

        return redirect()->back();
    }
    // PackageRepository.php
    ...
    public function getAllPackages()
    {
        $packages = $this->package->all();

        return $packages;
    }

    public function updatePackage($package_id)
    {
        $package = $this->package->find($package_id);
        $package->description = $this->request->description;
        $package->save();

        return $package;
    }
{{1}}

" testIndex()"的一部分的工作原理。

但接下来,我想测试" testUpdate()"的一部分。

我该怎么办?

请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

像这样

$this->mock
        ->shouldReceive('updatePackage')
        ->with(1)
        ->once()
        ->andReturn($expected);

$actual = $this->target->update(1);

$this->assertRedirect('edit page url');

use DatabaseTransactions in top of class

$id = DB::table('your_table')->insertGetId(['description' => 'old'])

request()->set('description', 'test');
$actual = $this->target->update(id);

$this->assertDatabaseHas('your_table', [
    'id' => $id,
    'description' => 'test'
]);