在这里,我研究了许多关于堆栈溢出的相同思路的问题,但无法找到解决这个特定问题的方法。
一般来说,我对单元测试非常陌生,所以这个错误可能(希望)对有更多经验的人来说是显而易见的。
以下是问题所在:
我有一个ResourceController,它使用Depedency将类注入构造函数。
public function __construct(ResourceAPIInterface $api)
{
$this->api = $api;
}当在控制器中调用该API时,注入的类执行一些业务逻辑,并返回一个雄辩的集合。
public function index($resource, $version)
{
$input = Input::all();
//Populate Data
$data = $this->api->fetchAll($input);
//Format response
if($data->isEmpty()){
//Format response
$response = Response::make(" ", 204);
}else {
//Format response
$response = Response::make($data, 200);
}
//Set content-type in header
$response->header('Content-Type', 'application/json');
$response->header('Cache-Control', 'max-age=3600');
return $response;
}正如您可以从上面的代码中看到的,我需要这个响应是一个雄辩的响应,这样我就可以测试它是否是空的。实际上,FetchAll方法只返回表中所有记录的令人信服的排序。当我进行测试时,我能够模拟API,而不存在任何问题。然而,当我在嘲弄回应时,我真的希望这个回应是一个雄辩的集合,并且很难做到这一点。下面是测试的一个示例:
$course = Mockery::mock(new API\Entity\v1\Test);
$this->mock->shouldReceive('fetchAll')->once()->andReturn($course->all());
$this->mock->shouldReceive('name')->once()->andReturn('Course');
// Act...
$response = $this->action('GET', 'ResourceController@show');
// Assert...
$this->assertResponseOk(); 上面的方法是有效的,但是当我想对show进行同样的测试并模拟->first()的雄辩反应时,我会得到错误。
1) ResourceControllerTest::testshow
BadMethodCallException: Method Mockery_1_API_Entity_v1_Test_API_Entity_v1_Test::first() does not exist on this mock object我尝试通过以下方法来测试模型:
$course = Mockery::mock('Eloquent', 'API\Entity\v1\Test');
$response = $course->mock->shouldReceive('find')->with(1)->once()->andReturn((object)array('id'=>1, 'name'=>'Widget-name','description'=>'Widget description'));但是,当我在测试中运行它时,我会得到以下错误:
1) ResourceControllerTest::testIndex
BadMethodCallException: Method Mockery_1_API_Entity_v1_Test::getAttribute() does not exist on this mock object对于如何解决这个问题,有什么想法吗?此外,如果有更好的方法来测试雄辩的集合是否是空的,这可能解决我遇到的一些复杂性也是值得欢迎的。
发布于 2014-08-20 20:38:49
好吧,我想出了怎么做的办法:
public function testIndex($resource="course", $version="v1")
{
// Arrange...
$course = Mockery::mock('Eloquent', 'API\Entity\v1\Page')->makePartial();
$course->shouldReceive('isEmpty')->once()->andReturn(false);
$course->shouldReceive('all')->once()->andReturn($course);
$this->mock->shouldReceive('fetchAll')->once()->andReturn($course->all());
$this->mock->shouldReceive('name')->once()->andReturn('Course');
// Act...
$response = $this->action('GET', 'ResourceController@index');
// Assert...
$this->assertResponseOk();
}我能够执行PartialMock来避免getAttribute()错误。一旦我这样做了,我就开始得到错误:
Call to undefined method stdClass::isEmpty() 因此,我决定也对此进行模拟,并将整个模拟对象传递到对all命令的预期响应中。
然后,在API类的模拟中,$this-> mocked >我让它使用->all()方法返回模拟的雄辩集合。
这也适用于我为find($id)进行的另一个测试。但是,这个检查不需要isEmpty()检查,因此更容易模拟。
https://stackoverflow.com/questions/25411210
复制相似问题