I am trying a Mock Eloquent Model with Mockery. The model is entered into the controller through
__construct(Post $model){$this->model=$model}
Now I call the find() function in the controller
$post = $this->model->find($id);
And here is the test for PostsController
class PostsTest extends TestCase{ protected $mock; public function setUp() { parent::setUp(); $this->mock = Mockery::mock('Eloquent', 'Posts'); $this->app->instance('Posts', $this->mock); } public function tearDown() { Mockery::close(); } public function testGetEdit() { $this->mock->shouldReceive('find')->with(1)->once()->andReturn(array('id'=>1)); $this->call('GET', 'admin/posts/edit/1'); $this->assertViewHas('post', array('id'=>1)); } }
Running PhpUnit gives me an error:
Fatal error: Using $this when not in object context in ...\www\l4\vendor\mockery\mockery\library\Mockery\Generator.php(130) : eval()'d code on line 73
This is obviously because find() declared as a static function. Now the code works without errors, so how can I successfully simulate the Eloquent model without its failure. Since we rely on dependency injection, I have to call find() non-statically, otherwise I could just do Post::find() .
One of the solutions I came across is to create a non-static replace for find() in BaseModel
public function nsFind($id, $columns = array('*')) { return self::find($id, $columns); }
But this is a big pain, since the function must have a different name!
Am I doing something wrong or do you have any better ideas?