gpt4 book ai didi

php - 在 laravel 5.8 中为 try catch 编写单元测试

转载 作者:行者123 更新时间:2023-11-28 20:00:47 25 4
gpt4 key购买 nike

我的 Controller 里有这样的东西:

public function method()
{
try {
$data = Model::method();

return $data;
} catch (Exception $e) {
return $e->getMessage();
}
}

当我正在寻找为此方法编写单元测试时,以这种方式:

public function testMethod()
{
$var = (new \App\Http\Controllers\MyController)->method();

$this->assertTrue(true);
}

我的问题是,当我在代码覆盖模式下运行 phpunit 时,它返回我的 Controller 代码中的 catch block 未被覆盖。

第一个问题是我应该如何覆盖 catch block ?

我的第二个问题是如何说 $var 值等于我定义的值。

最佳答案

如果你想测试 $var 是否等于某个特定的东西,你可以使用 $this->assertEquals(mixed $expected, mixed $actual[, string $message = ''])

因此,如果您希望 $var 等于 'hello',您将编写以下内容:

$this->assertEquals('hello', $var, 'optional message to display on test failure'

您可以阅读有关assertEquals 的更多信息here .

就你的第一个问题而言。如果您可以通过将特定参数传递给 Controller ​​方法来抛出异常,那么这是最简单的。否则,您需要模拟 Model 并在函数被调用时抛出异常以强制调用 catch block 。

您可以按照以下方式进行操作:

    $mock = Mockery::mock('\App\Model');
$mock->shouldReceive('method')->once()
->andThrow(new \Exception('Fun exception'));
$this->app->instance('\App\Model', $mock);

关于php - 在 laravel 5.8 中为 try catch 编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com