laravel - 测试 Laravel Controller 的 try catch

标签 laravel testing mocking automated-tests mockery

我正在使用 Laravel 5.7 并且有这个 Controller

public function upload(Request $request)
{
    $fileData   = $request->getContent();
    $fileName   = uniqid().'.xlsx';

    try {
        // save file locally
        Storage::disk('local')->put($fileName, $fileData);

        // dispatch to queue
        AnyJob::dispatch($fileName);

        // insert in import_statuses table for status checking
        AnyModel::create([
            'job_id'  => $fileName
        ]);

    } catch (\Exception $e) {
        error_log($e);

        return response()->json([
            'error' => 'Could not save file or queue not found.'
        ], 500);
    }

    return response()->json([
        'status' => 'OK',
        'jobId'  => $fileName,
    ]);
}

我正在尝试创建一个进入陷阱的测试,但我无法让它工作。

我已经尝试模拟 Storage 并期望方法 diskput 被调用,但它总是提示其他方法被调用而不是预期。

我还尝试以多种方式模拟 AnyJobAnyModel 但这似乎并不影响 $this->post.

这是我现在的测试方法:

public function testUploadException()
{
    $xlsxFile = UploadedFile::fake()->create('test.xlsx', 100);

    // ignore Storage and Job real work
    \Illuminate\Support\Facades\Storage::fake();
    $this->withoutJobs();

    $mock = Mockery::mock('\App\AnyModel');
    $mock
        ->shouldReceive('create')->times(3)
        ->andThrow(new \Exception('any error'));

    $this->app->instance('\App\AnyModel', $mock);

    $response = $this
        ->withHeaders(['content-type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'])
        ->post('/api/upload', [$xlsxFile]);

    $response
        ->assertStatus(500)
        ->assertJson([
            'error' => 'Could not save file or queue not found.'
        ]);
}

它返回了什么

root@3e5d84a4db42:/application/api# vendor/bin/phpunit 
PHPUnit 7.5.4 by Sebastian Bergmann and contributors.

....F                                                               5 / 5 (100%)

Time: 2.62 seconds, Memory: 20.00MB

There was 1 failure:

1) Tests\Feature\UploadTest::testUploadException
Expected status code 500 but received 200.
Failed asserting that false is true.

/application/api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133
/application/api/tests/Feature/UploadTest.php:50

FAILURES!
Tests: 5, Assertions: 8, Failures: 1.

最佳答案

这行不通的主要原因是您没有从 IoC 解析模型,例如使用 app() 或依赖注入(inject)。这将适用于 facades 但不适用于 Eloquent 模型。

您可以将 Controller 方法定义更改为以下内容以从容器中解析类:

public function upload(Request $request, AnyModel $anyModel)

那么您对 ​​create 的调用将是:

$anyModel->create([
    'job_id'  => $fileName
]);

您的测试中也存在一些问题:

  1. 该类的完全限定名称是 'App\AnyModel' 而不是 '\App\AnyModel'。我建议使用 ::class而不是使用字符串,即 AnyModel::class(确保您已导入该类)。
  2. 您似乎只调用了一次 create(),所以 ->times(3) 会引发错误。

关于laravel - 测试 Laravel Controller 的 try catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174891/

相关文章:

javascript - 通过 webpack 为 Laravel 添加 moment

Laravel Forge 部署脚本失败并显示 'command not found'

testing - 测试 Ember.js 应用程序时如何模拟后退按钮?

java - 我应该如何测试 JApplets 和 Applets?

unit-testing - 我是否应该通过单元测试覆盖代码,即使它已经被集成测试覆盖?

angular - 是否可以模拟 typescript 装饰器?

php - Laravel 5.6 图片上传,将文章 slug 作为图片名称保存在数据库中

php - 将数据库列名称与 json 键匹配的简单方法?

.net - 如何测试依赖于事件发生日期的功能?

c# - Ninject:使用 NSubstitute 自动模拟?