如何使用Laravel和Mocky测试存储函数
我想使用PHPUnit和mockry测试Laravel5.6中的存储库模式 这是我的代码:如何使用Laravel和Mocky测试存储函数,laravel,laravel-5,phpunit,mockery,Laravel,Laravel 5,Phpunit,Mockery,我想使用PHPUnit和mockry测试Laravel5.6中的存储库模式 这是我的代码: // PackageControllerTest.php namespace Tests\Feature; use Tests\TestCase; use App\Contracts\PackageInterface; use App\Http\Controllers\PackageController; use Illuminate\Database\Eloquent\Collection; cl
// 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;
}
}
“testIndex()”部分工作正常 但是接下来,我想测试“testUpdate()”的部分 我该怎么办 请帮忙,谢谢。像这样
$this->mock
->shouldReceive('updatePackage')
->with(1)
->once()
->andReturn($expected);
$actual = $this->target->update(1);
$this->assertRedirect('edit page url');
或
谢谢你的回答。我试了第一个。但出现错误:
属性[title]在此集合实例上不存在。
“title”是packages表中的第一个字段。我应该先迁移数据库吗?但我认为我可以在不接近数据库的情况下进行测试。这就是我使用嘲弄的原因(感谢您的回复。我已上载。抱歉,显示的错误不是[title],而是[login]。此集合实例上不存在属性[login]。
“login”是packages表中的第一个字段。
// 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;
}
$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'
]);