如何测试一个从Laravel 5软件包中从数据库获取数据的函数?

时间:2019-03-17 13:50:01

标签: laravel unit-testing laravel-5 phpunit

我正在研究Laravel 5软件包,并且正在编写测试,我试图测试一个从DB获取数据的函数。

public function getPhotoDatasFromDb()
{
    $ret = GalleryImage::get()->keyBy('file_name');
    return $ret;
}

返回的值应采用以下格式:

Collection {#416 ▼
  #items: array:2 [▼
    "IMG_1979.jpg" => GalleryImage {#423 ▼}
        "alt_text" => "example alt text"
        "description" => "lorem ipsum"
    "IMG_1980.jpg" => GalleryImage {#424 ▶}
  ]
}

我已经在其他Laravel应用程序中进行数据库测试的经验。

我的问题是:由于我正在编写一个程序包,并且在开发环境中我没有数据库实例,所以我想知道什么是测试它的最佳方法?

如果可以帮助您更全面地了解情况,则会通过此迁移在应用程序中创建数据库表:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateGalleryImagesTable extends Migration
{
    public function up()
    {
        Schema::create('gallery_images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_name')->unique();
            $table->text('description')->nullable();
            $table->string('alt')->nullable();
            $table->string('video_link')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('gallery_images');
    }
}

这是关联的模型

<?php

namespace DavideCasiraghi\ResponsiveGallery;

use Illuminate\Database\Eloquent\Model;

class GalleryImage extends Model
{
    protected $fillable = [
        'file_name', 'description', 'alt', 'video_link',
    ];
}

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。 我将其发布,以免对其他人有帮助。

这是我的测试:

    /** @test */
    public function it_gets_photos_from_db()
    {
        $gallery = new ResponsiveGalleryFactory();
        $dbImageDatas = $gallery->getPhotoDatasFromDb();
        $this->assertStringContainsString($dbImageDatas['DSC_9470.jpg']->description, 'Photo description');
    }

要使其正常工作,我必须在测试类的开头配置数据库:

    /**
     * Create the tables this model needs for testing.
     */
    public static function setUpBeforeClass() : void
    {
        $capsule = new Capsule;

        $capsule->addConnection([
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
        ]);

        $capsule->setAsGlobal();
        $capsule->bootEloquent();

        Capsule::schema()->create('gallery_images', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_name')->unique();
            $table->text('description')->nullable();
            $table->string('alt')->nullable();
            $table->string('video_link')->nullable();
            $table->timestamps();
        });

        Model::unguard();

        GalleryImage::create([
            'file_name' => 'DSC_9470.jpg',
            'description' => 'Photo description',
            'alt_text' => 'Photo alt text',
            'video_link' => 'https://www.youtube.com/fsda234',
        ]);
    }