Php 在Laravel中模拟验证器,模拟返回对非对象上的成员函数的调用
我正在尝试为我的REST控制器实现一些单元测试。在我使用验证器外观之前,一切正常。索引和显示测试工作正常 我得到的错误是:Php 在Laravel中模拟验证器,模拟返回对非对象上的成员函数的调用,php,laravel,mockery,Php,Laravel,Mockery,我正在尝试为我的REST控制器实现一些单元测试。在我使用验证器外观之前,一切正常。索引和显示测试工作正常 我得到的错误是: Fatal Error: Call to a member function setAttributeName() on a non-object in D:\....\controllers\AllergyController. 我的代码是: //Unit test class AllergyControllerTest extends TestCase { p
Fatal Error: Call to a member function setAttributeName() on a non-object in D:\....\controllers\AllergyController.
我的代码是:
//Unit test
class AllergyControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->allergy = $this->mock('App\Modules\Patient\Repositories\IAllergyRepository');
}
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
public function testIndex()
{
$this->allergy->shouldReceive('all')->once();
$this->call('GET', 'api/allergy');
$this->assertResponseOk();
}
public function testShow()
{
$this->allergy->shouldReceive('find')->once()->andReturn(array());
$this->call('GET', 'api/allergy/1');
$this->assertResponseOk();
}
public function testStore()
{
$validator = Mockery::mock('stdClass');
Validator::swap($validator);
$input = array('name' => 'foo');
$this->allergy->shouldReceive('create')->once();
$validator->shouldReceive('make')->once();
$validator->shouldReceive('setAttributeNames')->once();
$this->call('POST', 'api/allergy', $input);
$this->assertResponseOk();
}
}
我的控制器:
class AllergyController extends \App\Controllers\BaseController
{
public function __construct(IAllergyRepository $allergy){
$this->allergy = $allergy;
}
public function index()
{
...
}
public function show($id)
{
...
}
public function store()
{
//define validation rules
$rules = array(
'name' => Config::get('Patient::validation.allergy.add.name')
);
//execute validation rules
$validator = Validator::make(Input::all(), $rules);
$validator->setAttributeNames(Config::get('Patient::validation.allergy.messages'));
if ($validator->fails()) {
return Response::json(array('status' => false, 'data' => $validator->messages()));
} else {
$allergy = $this->allergy->create(Input::all());
if ($allergy) {
return Response::json(array('status' => true, 'data' => $allergy));
} else {
$messages = new \Illuminate\Support\MessageBag;
$messages->add('error', 'Create failed! Please contact the site administrator or try again!');
return Response::json(array('status' => false, 'data' => $messages));
}
}
}
}
我似乎不明白它为什么会抛出这个错误。当我使用普通api调用控制器时,它工作正常
非常感谢您的帮助 您可能希望从stubbed
make
调用返回验证程序double
$validator->shouldReceive('make')->once()->andReturn($validator);