samedi 26 mai 2018

How can I test a store function with Laravel and Mockery

I want to test a repository pattern in Laravel 5.6 using PHPUnit and Mockery.

This is my code:

// PackageControllerTest.php

namespace Tests\Feature;

use Tests\TestCase;
use App\Contracts\PackageInterface;
use App\Http\Controllers\PackageController;
use Illuminate\Database\Eloquent\Collection;

class PackageControllerTest extends TestCase
{
    protected $mock;
    protected $target;

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

        parent::initDatabase();

        $this->mock = $this->initMock(PackageInterface::class);
        $this->target = $this->app->make(PackageController::class);
    }

    public function testIndex()
    {
        $expected = new Collection([
            ['name' => 'Name 1', 'html_url' => 'HTML URL 1'],
            ['name' => 'Name 2', 'html_url' => 'HTML URL 2'],
            ['name' => 'Name 3', 'html_url' => 'HTML URL 3'],
        ]);

        $this->mock
            ->shouldReceive('getAllPackages')
            ->once()
            ->andReturn($expected);

        $actual = $this->target->index()->packages;

        $this->assertEquals($expected, $actual);
    }

    public function testUpdate()
    {
        //
    }

    public function tearDown()
    {
        parent::resetDatabase();

        $this->mock = null;
        $this->target = null;
    }
}
    // 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;
    }

It works.

But next, I want to test a update function.

How can I do?

Please help, thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire