php Laravel mocking路由参数

jv4diomz  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(91)

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

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

这是我试图通过的模拟考试。我尝试做的所有事情都显示路由上的user属性为null。

$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());
});
yshpjwxd

yshpjwxd1#

你没有按照你应该做的那样测试:

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

因此,我将编写一个 * 特性测试 *,向您展示您应该做的事情,因此请记住,我将编写假路由和工厂,这些路由和工厂可能与您设置的不同或甚至没有设置(我将使用Laravel 8PHP 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%测试。

相关问题