首页 > 解决方案 > Laravel 测试商店方法

问题描述

您好,我想在 laravel 中测试一个 store 方法。在 store 方法中有简单的数据和图像。伪造者也生成所有数据和图像,但验证者不接受图像。为什么会这样?伪造者生成正确的图像名称和扩展名。

这是测试用例

    public function test_an_authenticated_user_can_add_new_companie () 
    {
        $companies = factory(Companies::class)->create();

        $company = $companies->toArray();

        $this->actingAs($this->user);
        $response = $this->postJson('/home/companies/create/add', $company);
        $response->assertStatus(302);
    }

这里是工厂

        'name' => $faker->company,
        'email' => $faker->email,
        'logo' => $faker->image(public_path('img\logos'), 100, 100, null, false),
        'website' => $faker->url,

标签: phplaravelimagetesting

解决方案


Faker 会保存一个临时图像并给你一个文件路径,这不是你想要的。

为了测试上传图像,您应该UploadedImage::fake()改用。由于您需要伪造,图像类如何通过API调用来代替。

$data = [
    'logo' => UploadedFile::fake()->image('logo.jpg'),
    ...
];

$response = $this->postJson('/home/companies/create/add', $data);

要检查文件是否实际保存,您可以伪造并断言它已完成。

邮局电话之前。

Storage::fake('public');

通话后的断言。

Storage::disk('public')->assertExists('img\logos\logo.jpg');

推荐阅读