Been looking all over the internet but don't seem to find an answer to my problem. I've been diving into testing controllers in Laravel using PHPUnit and Mockery. However, I don't seem to get my Eloquent based models mocked correctly. I did manage to mock my Auth::user() the same way, although this is not used in the test below.
Function in AddressController that needs to be tested:
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 containing setUp and mock method
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 extending 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);
}
}
The error it keeps throwing is:
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.
Perhaps anyone has an idea?