测试失败的交易

问题描述 投票:0回答:1
我想测试

catch

块。为了实现这一目标,我试图嘲笑
DB
立面:

test('volunteer failed registration transaction', function () {
    $this->withoutExceptionHandling();
    Log::spy();

    DB::partialMock()
        ->shouldReceive('transaction')
        ->once()
        ->andThrow(new \Exception('Transaction failed'));

    $response = $this->post(route('register.store'), [
        'firstname' => 'Test',
        'lastname' => 'User',
        'email' => '[email protected]',
        'password' => 'password',
        'password_confirmation' => 'password',
        'address' => 'street 12',
        'zip' => '12345',
        'city' => 'city',
    ]);

    $response->assertRedirect();
    $response->assertSessionHas('error', 'An error occurred while registering the user');

    Log::shouldHaveReceived('error')
        ->once()
        ->with('Volunteer registration failed', [
            Mockery::on(fn ($args) => isset($args['error']) &&
                isset($args['trace'])
            ),
        ]
        );
});
我得到这个错误:

FAILED Tests\Feature\RegistrationTest > volunteer failed registration transaction ErrorException Trying to access array offset on value of type null at vendor\laravel\framework\src\Illuminate\Database\DatabaseManager.php:366 362▕ * @return string 363▕ */ 364▕ public function getDefaultConnection() 365▕ { ➜ 366▕ return $this->app['config']['database.default']; 367▕ } 368▕ 369▕ /** 370▕ * Set the default connection name.
我也尝试嘲笑此功能:

DB::partialMock() ->shouldReceive('getDefaultConnection') ->andReturn($this->app['config']['database.default']);

但是,我收到此消息:

FAILED Tests\Feature\RegistrationTest > volunteer failed registration transaction ErrorException Trying to access array offset on value of type null at vendor\laravel\framework\src\Illuminate\Database\DatabaseManager.php:202 198▕ 199▕ // To get the database connection configuration, we will just pull each of the 200▕ // connection configurations and get the configurations for the given name. 201▕ // If the configuration doesn't exist, we'll throw an exception and bail. ➜ 202▕ $connections = $this->app['config']['database.connections']; 203▕ 204▕ if (is_null($config = Arr::get($connections, $name))) { 205▕ throw new InvalidArgumentException("Database connection [{$name}] not configured."); 206▕ } 1 vendor\laravel\framework\src\Illuminate\Database\DatabaseManager.php:168 2 vendor\laravel\framework\src\Illuminate\Database\DatabaseManager.php:95

	

在我看来,您通常不需要嘲笑整个DB立面。取而代之的是,您可以在实际上在交易中像

User::create
一样在实际上被调用的地方抛出一个异常。如果pr抛出异常,它将被捕获在您的控制器的捕获块中。例如:
php laravel testing mockery php-pest
1个回答
0
投票

然后致电您的

User::shouldReceive('create')
    ->once()
    ->andThrow(new \Exception('Mocked create failure'));
路由以触发注册逻辑。这样,例外将在交易内部冒泡,并且应测试您的捕获块,而无需模拟整个DB立面。
	

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