1

我正在尝试做:

$this->assertFileExists($user->getFirstMedia()->getPath());在我的测试中。但是当我运行它时,我得到了这个错误:

BadMethodCallException: Call to undefined method App\Models\User::getFirstMedia().

我愿意:

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

我也这样做:

class AssortmentTest extends TestCase implements hasMedia
{
    use RefreshDatabase;
    use InteractsWithMedia;

据我所知,我正在使用正确的特征。我在这里做错了什么?

编辑:

我的测试:

public function testUserCanUploadFile()
    {
        $this->withoutExceptionHandling();
        $user = $this->signIn();

        Storage::fake('public'); //Mock a disk
        $file = UploadedFile::fake()->image('test.jpg'); //Upload a fake image.

        $assortmentAttributes = Assortment::factory()->raw(); // Use the assortment factory.
        $assortmentAttributes['image_path'] = $file; // Add a additional field in the assortment factory.

        $this->post(route('assortments.store'), $assortmentAttributes)->assertRedirect(); // Post the fields to the assortmentcontroller store method.
        //Storage::disk('public')->assertExists($file->hashName()); // Check if the field exists.

        $this->assertFileExists($user->getFirstMedia()->getPath());
    }

我的商店方法控制器代码:

if ($request->hasFile('image')) {
            $image = $request->file('image'); //request the file
            $fileName = md5_file($image . microtime()) . '.' . $image->getClientOriginalExtension(); //use md5 for security reasons and get the extension.
            $image->storeAs('', $fileName, 'public'); //store the file in the public folder disk.
        } 
        
         if ($request->wantsJson()) {
             return response([], 204);
        }
4

1 回答 1

3

You are implementing your traits in a TestCase, that is not correct. If you are accessing your users media, you should implement the traits on the User.php model class, its either located in app/User.php or app/Models/User.php.

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class User extends Authenticatable implements HasMedia {
   use InteractsWithMedia;
}
于 2021-01-03T16:35:34.047 回答