【发布时间】:2016-08-17 20:06:41
【问题描述】:
一直在寻找整个互联网,但似乎没有找到我的问题的答案。我一直在使用 PHPUnit 和 Mockery 在 Laravel 中测试控制器。但是,我似乎没有正确模拟基于 Eloquent 的模型。我确实设法以同样的方式模拟了我的 Auth::user(),尽管这在下面的测试中没有使用。
AddressController 中需要测试的函数:
public function edit($id)
{
$user = Auth::user();
$company = Company::where('kvk', $user->kvk)->first();
$address = Address::whereId($id)->first();
if(is_null($address)) {
return abort(404);
}
return view('pages.address.update')
->with(compact('address'));
}
ControllerTest 包含 setUp 和 mock 方法
abstract class ControllerTest extends TestCase
{
/**
* @var \App\Http\Controllers\Controller
*/
protected $_controller;
public function setUp(){
parent::setUp();
$this->createApplication();
}
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
protected function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
}
AddressControllerTest 扩展 ControllerTest
class AddressControllerTest extends ControllerTest
{
/**
* @var \App\Models\Address
*/
private $_address;
/**
* @var \App\Http\Controllers\AddressController
*/
protected $_controller;
public function setUp(){
parent::setUp();
$this->_controller = new AddressController();
$this->_address = factory(Address::class)->make();
}
public function testEdit404(){
$companyMock = $this->mock(Company::class);
$companyMock
->shouldReceive('where')
->with('kvk', Mockery::any())
->once();
->andReturn(factory(Company::class)->make([
'address_id' => $this->_address->id
]));
$addressMock = $this->mock(Address::class);
$addressMock
->shouldReceive('whereId')
->with($this->_address->id)
->once();
->andReturn(null);
//First try to go to route with non existing address
$this->action('GET', 'AddressController@edit', ['id' => $this->_address->id]);
$this->assertResponseStatus(404);
}
}
它不断抛出的错误是:
1) AddressControllerTest::testEdit404
Mockery\Exception\InvalidCountException: Method where("kvk", object(Mockery\Matcher\Any)) from Mockery_1_Genta_Models_Company should be called exactly 1 times but called 0 times.
也许有人有想法?
【问题讨论】:
-
用 $this->action() 方法替换了 $this->call() 方法,同时检查我的控制器方法是否被调用并且在替换后它确实调用了。但是问题仍然存在。
标签: php unit-testing laravel eloquent mockery