无法测试事件是不是具有 Laravel 5 和 PHPUnit 的属性
Posted
技术标签:
【中文标题】无法测试事件是不是具有 Laravel 5 和 PHPUnit 的属性【英文标题】:Unable to test that an Event has properties with Laravel 5 and PHPUnit无法测试事件是否具有 Laravel 5 和 PHPUnit 的属性 【发布时间】:2015-07-02 01:28:08 【问题描述】:我正在尝试测试我的事件在触发时是否具有正确的属性。我能够确定触发了一个事件,但不能确定发送了正确的属性。
PHP
<?php
use App\Events\ManifestRecordCreated;
use App\ManifestFile;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;
class ManifestTest extends TestCase
/**
* This is the test I'd like to perfom.
*/
public function testOhLookMyEventGetsTheRightProperties()
Event::shouldReceive('fire')->once()->withArgs(array('App\\Events\\ManifestRecordCreated', array (
'poseId' => 2,
'stateId' => 1,
'manifestId' => 1,
)
));
Event::fire(new ManifestRecordCreated(2, 1, 1));
/**
* Test that the event is fired.
*/
public function testOnlyOneThatWorks()
Event::shouldReceive('fire')->once()->with(Mockery::any());
Event::fire(new ManifestRecordCreated(2, 1, 1));
/**
* I'd like to test if the evnt is getting the right arguments.
*/
public function testGraspingAtStraws()
$args = array ('App\Events\ManifestRecordCreated' => array (
'class' => 'App\Events\ManifestRecordCreated',
'properties' => array (
'poseId' => 2,
'stateId' => 1,
'manifestId' => 1,
),
'getters' => array (),
),
);
Event::shouldReceive('fire')->once()->withArgs($args);
Event::fire(new ManifestRecordCreated(2, 1, 1));
/**
* I don't think I need this, but I did read it somewhere in my search.
*/
public function tearDown()
\Mockery::close();
PHPUnit测试结果
1) ManifestTest::testOhLookMyEventGetsTheRightProperties
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Illuminate_Events_Dispatcher::fire(object(App\Events\ManifestRecordCreated)). Either the method was unexpected or its arguments matched no expected argument list for this method
Objects: ( array (
'App\\Events\\ManifestRecordCreated' =>
array (
'class' => 'App\\Events\\ManifestRecordCreated',
'properties' =>
array (
'poseId' => 2,
'stateId' => 1,
'manifestId' => 1,
),
'getters' =>
array (
),
),
))
2) ManifestTest::testGraspingAtStraws
ErrorException: Undefined offset: 0
Laravel 5 docs 不是很有帮助。
This approach 忽略除事件之外的所有内容。
【问题讨论】:
【参考方案1】:ErrorException: Undefined offset: 0
的问题是该数组是使用命名键传递的,而不是作为您希望传递的参数的 0 到 X 列表。 (以'App\\Events\\ManifestRecordCreated'
为键名)
通常您只需传入一个列表,但使用对象参数匹配可能会失败,因为它不是同一个实例,因此您可以使用 hamcrest equalTo 方法来比较对象值,而不是实例
有点像
public function testObjectValuesEqual()
Event::shouldReceive('fire')->once()->withArgs([Matchers::equalTo(new ManifestRecordCreated(2, 1, 1))]);
Event::fire(new ManifestRecordCreated(2, 1, 1));
【讨论】:
以上是关于无法测试事件是不是具有 Laravel 5 和 PHPUnit 的属性的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 5 CORS - XMLHttpRequest 无法加载 http://myapi.com。预检响应具有无效的 HTTP 状态代码 500