在功能测试中模拟类实例化

时间:2019-03-05 17:28:15

标签: laravel phpunit mockery

我目前正在开发我的第一个Laravel项目-一个服务端点,该服务端点根据S3中保存的记录返回资源。该服务不需要数据库,但我的想法是,可以通过将逻辑移至“模型”来保持控制器的外观。然后,我可以通过模仿一些标准的活动记录调用来访问资源。

从功能上讲,该实现按预期工作,但我在模拟方面遇到问题。

我正在使用一个库来创建签名的CloudFront URL,但是它是作为静态方法访问的。当我第一次开始编写功能测试时,我发现我无法使用静态方法。我尝试使用Mockery进行类别名,但没有运气-我仍然在使用static方法。因此,我尝试将静态方法包装在一个小类中,假设模拟该类会更容易。不幸的是,我遇到了同样的问题。我尝试嘲笑的东西被打了,好像我没有嘲笑一样。

此堆栈溢出文章提供了有关如何使用类别名的示例,但我无法使其正常工作。 What is the difference between overload and alias in Mockery?

我在做什么错?我更希望使用嘲讽别名来工作,但是实例嘲讽会很好。请指出正确的方向。预先感谢您的帮助。

控制器

// app/Http/Controllers/API/V1/RecordingController.php
class RecordingController extends Controller {
    public function show($id){
        return json_encode(Recording::findOrFail($id));
    }
}

型号

// app/Models/Recording.php
namespace App\Models;

use Mockery;
use Carbon\Carbon;
use CloudFrontUrlSigner;
use Storage;
use Illuminate\Support\Arr;

class Recording
{
    public $id;
    public $url;

    private function __construct($array)
    {
        $this->id = $array['id'];
        $this->url = $this->signedURL($array['filename']);
    }

    // imitates the behavior of the findOrFail function
    public static function findOrFail($id): Recording
    {
        $filename = self::filenameFromId($id);
        if (!Storage::disk('s3')->exists($filename)) {
            abort(404, "Recording not found with id $id");
        }

        $array = [
            'id' => $id,
            'filename' => $filename,
        ];

        return new self($array);
    }

    // imitate the behavior of the find function
    public static function find($id): ?Recording
    {
        $filename = self::filenameFromId($id);
        if (!Storage::disk('s3')->exists($filename)){
            return null;
        }

        $array = [
            'id' => $id,
            'filename' => $filename,
        ];

        return new self($array);
    }

    protected function signedURL($key) : string
    {
        $url = Storage::url($key);
        $signedUrl = new cloudFrontSignedURL($url);
        return $signedUrl->getUrl($url);
    }
}

/**
 * wrapper for static method for testing purposes
 */
class cloudFrontSignedURL {
    protected $url;
    public function __construct($url) {
        $this->url = CloudFrontUrlSigner::sign($url);
    }
    public function getUrl($url) {
        return $this->url;
    }
}

测试

// tests/Feature/RecordingsTest.php
namespace Tests\Feature;

use Mockery;
use Faker;
use Tests\TestCase;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\WithFaker;

/* The following is what my test looked like when I wrapped CloudFrontUrlSigner 
 * in a class and attempted to mock the class
 */
class RecordingsTest extends TestCase
{
    /** @test */
    public function if_a_recording_exists_with_provided_id_it_will_return_a_URL()
    {
        $recordingMock = \Mockery::mock(Recording::class);
        $faker = Faker\Factory::create();
        $id = $faker->numberBetween($min = 1000, $max = 9999);

        $filename = "$id.mp3";
        $path = '/api/v1/recordings/';
        $returnValue = 'abc.1234.com';

        $urlMock
            ->shouldReceive('getURL')
            ->once()
            ->andReturn($returnValue);

        $this->app->instance(Recording::class, $urlMock);

        Storage::fake('s3');
        Storage::disk('s3')->put($filename, 'this is an mp3');
        Storage::disk('s3')->exists($filename);

        $response = $this->call('GET', "$path$id");
        $response->assertStatus(200);
    }
}

// The following is what my test looked like when I was trying to alias CloudFrontUrlSigner
{
    /** @test */
    public function if_a_recording_exists_with_provided_id_it_will_return_a_URL1()
    {
        $urlMock = \Mockery::mock('alias:Dreamonkey\cloudFrontSignedURL');
        $faker = Faker\Factory::create();
        $id = $faker->numberBetween($min = 1000, $max = 9999);

        $filename = "$id.mp3";
        $path = '/api/v1/recordings/';
        $returnValue = 'abc.1234.com';

        $urlMock
            ->shouldReceive('sign')
            ->once()
            ->andReturn($returnValue);

        $this->app->instance('Dreamonkey\cloudFrontSignedURL', $urlMock);

        Storage::fake('s3');
        Storage::disk('s3')->put($filename, 'this is an mp3');
        Storage::disk('s3')->exists($filename);

        $response = $this->call('GET', "$path$id");
        $response->assertStatus(200);
    }
}

phpunit

$ phpunit tests/Feature/RecordingsTest.php --verbose

...

There was 1 failure:

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

/Users/stevereilly/Projects/media-service/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133
/Users/stevereilly/Projects/media-service/tests/Feature/RecordingsTest.php:85
/Users/stevereilly/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:206
/Users/stevereilly/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:162

1 个答案:

答案 0 :(得分:0)

您得到500,这意味着代码有问题。只是通过扫描它,我注意到您在filenameFromId类上缺少一个Recordings方法,并且Test正在创建一个名为$recordingMock的模拟,但是您尝试使用$urlMock 。尝试先解决这些问题。
然后,您在嘲笑该类,但从未在应用程序中替换过它(显然您是在旧测试中完成的)。
通常,您在进行模拟时要遵循以下步骤:
1.模拟课程
2.告诉Laravel每当有人请求时,用您的模拟代替类
3.对模拟进行断言