Project-Flyer-17-Unit-Testing

跟随 Jeffrey Way 的视频学习,脑子不好,一些细节容易忘记,这里记录下来。相关视频在 laracasts.com
课程名称:Build “ProjectFlyer” With Me(17)

这一节:单元测试!

我们添加一个针对 AddPhotoToFlyer 的测试类tests/AddPhotoToFlyerTest.php,因为要测试上传,所以要引用 UploadFile,打开 UploadFile.php,添加引用:

use App\AddPhotoToFlyer;
use Symfony\Component\HttpFoundation\File\UploadFile;

对照 AddPhotoToFlyer.php 写测试方法,最终该方法为:

<?php

namespace App;

use App\AddPhotoToFlyer;
use Symfony\Component\HttpFoundation\File\UploadFile;
use Mockery as m;

class AddPhotoToFlyerTest extends TestCase
{
/** @test */
function it_()
{
$flyer = factory(App\Flyer::class)->create();

$file = m::mock(UploadFile::class, [
'getClientOriginName' => 'foo',
'getClientOriginExtension' => 'jpg'

]);

$file->shouldReceive('move')
->once()
->with('uploads/photos', 'nowfoo.jpg');

$thumbnail = m::mock(App\Thumbnail::class);

$thumbnail->shouldReceive('make')
->once()
->with('uploads/photos/newfoo.jpg', 'uploads/photos/tn-newfoo.jpg');

$form = new AddPhotoToFlyer($flyer, $file, $thumbnail);

$form->save();

$this->assertEquals(1, $flyer->photos);
}

function time()
{
return 'now';
}
}

然后在 Homestead 虚拟机网站根目录下运行:

phpunit tests/AddPhotoToFlyerTest.php

看到错误信息为:App\TestCase没找到。修改:

class AddPhotoToFlyerTest extends TestCase

为:

class AddPhotoToFlyerTest extends \TestCase

报错 it_() 方法错误,存在未定义方法。修改 it_() 方法名为:it_processes_a_form_to_add_a_photo_to_a_flyer
还是报刚才的错误,注意到我们已经有了 namespace 定义为 App,所以可以把it_方法里面的App\删了。
继续报错:

ErrorException: Argument 2 passed to App\AddPhotoToFlyer::construct() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, instance of Mockery_0Symfony_Component_HttpFoundation_File_UploadFile given, called in /home/vagrant/Code/flyer.dev/tests/AddPhotoToFlyerTest.php on line 32 and defined

修改:

use Symfony\Component\HttpFoundation\File\UploadFile;

为:

use Symfony\Component\HttpFoundation\File\UploadedFile;

还是报上面的错误,找到问题是出在这里:

$file = m::mock(UploadedFile::class, [
'getClientOriginName' => 'foo',
'getClientOriginExtension' => 'jpg'

]);

修改为:

$file = m::mock(UploadedFile::class, [
'getClientOriginalName' => 'foo',
'getClientOriginalExtension' => 'jpg'
]);

显示错误:

Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Symfony_Component_HttpFoundation_File_UploadedFile::move(“uploads/photos”, “c89492227ba6eec8970354d0c9ae495b53fb0f4d.jpg”). Either the method was unexpected or its arguments matched no expected argument list for this method

0%