Laravel 模拟路由参数

问题描述 投票:0回答:1

我目前正在对我的一些表单验证进行单元测试,并且需要模拟路由参数,以便它可以通过测试。我已经为请求设置了我认为正确的期望,但我没有做正确的事情。

Rule::unique('users')->ignore($this->route('user')->id)

这是我试图通过的测试模拟。我尝试做的所有事情都出现了,因为路线上的用户属性为空。

$userMock = $this->mock(User::class)->expects()->set('id', 1);

$requestMock = $this->mock(Request::class)
        ->makePartial()
        ->shouldReceive('route')
        ->set('user', $user)
        ->once()
        ->andReturn(\Mockery::self());

$this->mock(Rule::class, function ($mock) use ($userMock, $requestMock) {
    $mock->expects()->unique('user')->andReturns(\Mockery::self());
    $mock->expects()->ignore($requestMock)->andReturns(\Mockery::self());
});
php laravel testing phpunit mockery
1个回答
2
投票

您没有进行应有的测试:

  • 当你测试与 Laravel 核心相关的东西时,你
    Feature test
  • 当你想测试你自己的
    class
    Job
    Command
    时,你
    Unit test
    (你可以使用PHPUnit的测试用例或Laravel的测试用例,所以在后一种情况下,你加载并有可用的框架,我 99% 的时间都使用这个)。
  • 当你想测试外部 API 时(即使它是
    localhost
    但它是其他系统),你就这样做
    Integration tests

所以,我将编写一个功能测试,向您展示您应该做什么,因此请记住,我将编写假路线和工厂,这些路线和工厂可能您已设置不同或什至没有设置(我将使用

Laravel 8
PHP 8
):

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ShowTest extends TestCase
{
    use RefreshDatabase;

    public function test_error_is_thrown_when_user_is_not_unique()
    {
        /**
         * Create a fake user so we have an
         * existing user in the DB because
         * that is what we want to test
         *
         * This should end up as last_name = Doe
         */
        User::factory()->create([
            'last_name' => $lastName = 'Doe'
        ]);

        /**
         * This is going to be our
         * logged in user and we will
         * send this data.
         *
         * Fake last_name so we do not
         * end up with Doe when faker runs.
         * 
         * @var User $ownUser
         */
        $ownUser = User::factory()->create(['last_name' => 'Lee']);

        /**
         * We will simulate sending an update
         * so we can change the last_name of
         * our logged in user, but there is
         * another user with the same last name
         */
        $response = $this->actingAs($ownUser)
            ->put("/fake/route/{$ownUser->id}", ['last_name' => $lastName]);

        /**
         * If you don't want to assert what error
         * is coming back, just
         * write ...Errors('last_name') but I
         * recommend checking what is giving back
         */
        $response->assertSessionHasErrors(['last_name' => 'Literal expected error string.']);
    }
}

我希望你明白我在这里测试的是什么。如果还有什么问题请追问。

另外,如果您可以分享您的真实代码,我可以与您一起编写测试并尝试对您的代码进行 100% 测试。

© www.soinside.com 2019 - 2024. All rights reserved.