【问题标题】:How to fail laravel route for unit testing?如何使 laravel 路由失败以进行单元测试?
【发布时间】:2017-10-25 22:03:25
【问题描述】:

我的控制器中有以下代码

public function store(CreateSpecialityRequest $request) 
{
    DB::beginTransaction();
    try {
        $speciality = $this->specialityRepository->create($request->all());
        DB::commit();

        return redirect()->route('specialities.index')
            ->with('success', 'Speciality Added successfully');
    } catch (\Exception $e) {
        DB::rollBack();
        return $e->getMessage();
        return redirect()->route('specialities.index')
            ->with('error', 'Specialities details updating failed');
    }

}

我的测试用例

$speciality = [
            'name' => $faker->name,
            'description' => $faker->sentence,
            'icon' => $uploadedFile
        ];

        $this->post('/specialities', $speciality)
            ->assertResponseStatus(302)
            ->assertRedirectedToRoute('specialities.index')
            ->assertSessionHas(['success' => 'Speciality Added successfully'])
            ->followRedirects()
            ->assertViewHas('specialities');

在我的代码覆盖率上,它表明我只覆盖了 try 块 我也想覆盖 catch 块。如何在单元测试中失败我的路线?进入 catch 块

【问题讨论】:

    标签: php unit-testing phpunit laravel-5.3


    【解决方案1】:

    您可以只传递一个空数组作为输入,create 方法应该抛出 QueryException

    $this->post('/specialities', []);
    

    您还应该查看您的 catch 块返回。您将立即返回异常消息,永远不会调用带有消息的重定向。

    return $e->getMessage();
    return redirect()->route('specialities.index')
                ->with('error', 'Specialities details updating failed');
    

    【讨论】:

    • 对于空数组,我有 formRequest 验证,我已经编写了测试。我在 create 方法中使用了 Mockery throw exception 来使我的测试用例失败。谢谢回复。
    猜你喜欢
    • 2010-10-19
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多