我正在为Laravel控制器方法编写单元测试,但无论我对->with(...)
做什么,我都会继续获取NoMatchingExpectationExceptions。正在测试的代码:
public function destroy($id) {
$foo = FooService::foo($id); //returns a Foo object (an Eloquent model)
$fooCollection = new Collection(array($foo));
$response = FooService::archive($fooCollection);
return Response::json($response);
}
单元测试:
public function testArchiveSingle() {
$foo = Mockery::mock('Foo', array('id' => 1));
$fooCollection = new \Illuminate\Database\Eloquent\Collection();
$fooCollection->add($foo);
FooService::shouldReceive('foo')->once()
->with(1)
->andReturn($foo);
//here's the shouldReceive that's throwing the error:
FooService::shouldReceive('archive')->once()
->with($this->anything())
->andReturn(array('result'=>'here'));
$response = $this->action('DELETE', 'FoosController@destroy',
array('site' => 12345, 'foos' => 1),
array());
$this->assertResponseOk();
$this->assertTrue($response->headers->contains('Content-Type', 'application/json'));
//other tests that are proprietary in nature go here
}
在->with()
我尝试传递$fooCollection
,$this->instanceOf('Collection')
,$this->instanceOf('\Illuminate\Database\Eloquent\Collection')
以及其他一些内容。我也尝试将$fooCollection
定义更改为new Collection
。
当我运行测试时,我得到:
Mockery \ Exception \ NoMatchingExpectationException:找不到Mockery_1_FooService :: archive(Illuminate \ Database \ Eloquent \ Collection)的匹配处理程序。方法是意外的,或者它的参数与此方法的预期参数列表没有匹配
当我在麻烦中删除->with(...)
时应该接受测试运行正常,但是失去了价值,因为它不会捕获一个意外存档太多的(理论)错误。
答案 0 :(得分:1)
您应该使用Mockery::any()
来匹配任何参数。 PHPUnit自己的模拟库使用$this->anything()
。请参阅manual。
FooService::shouldReceive('archive')->once()
->with(Mockery::any())
->andReturn(array('result'=>'here'));