【问题标题】:Write unit test for try catch in laravel 5.8在 laravel 5.8 中为 try catch 编写单元测试
【发布时间】:2020-02-24 01:14:19
【问题描述】:

我的控制器中有这样的东西:

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 时,它会返回未覆盖控制器代码中的 catch 块。

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

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

【问题讨论】:

    标签: php laravel testing phpunit


    【解决方案1】:

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

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

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

    你可以阅读更多关于assertEqualshere的信息。

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

    你可以通过以下方式做到这一点:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2020-10-13
      • 2020-06-14
      • 2015-06-15
      • 1970-01-01
      • 2013-12-19
      • 2019-08-10
      相关资源
      最近更新 更多