Bullying light models with find ()

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'); /*According to Jeffrey Way you have to add Eloquent in this function call to be able to use certain methods from model*/ $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?

+7
source share
2 answers

The mocking Eloquent models are a very complex thing. This is described in the book, but I specifically note that this is a stop loss. Better use repositories.

However, to answer your question, the problem is that you are not executing the layout inside the constructor. This is the only way to make it work. This is not perfect, and I would not recommend it.

+4
source

I think that is precisely why Jeffrey presents the repositories in his book Laravel Testing Decoded (chapter 10).

Mockery also contains a section on static methods in README, see https://github.com/padraic/mockery#mocking-public-static-methods

+2
source

All Articles