Support the ongoing development of Laravel.io →
IOC Architecture Testing

I am new to unit testing, and testing at all...

I am trying to follow the repository implementation with pagination from the book 'Implementing Laravel' by Chris Fidao.

I have problem for the controller testing (code below): I undestand that I have to mock, the EloquentArticle repository, something like this:

$mock->shouldReceive('byPage')->once();
Paginator::shouldReceive('make')->once();
$this->call('GET', 'home');
$this->assertViewHas('articles');

But then I have an error on the controller that $pagiData is not an object (for $pagiData->items)

So my questionsare maybe trivial but

  1. How to handle the returned value from the repository,
  2. How to handle the Paginator returned value

Here is an example of a repository:

class EloquentArticle implements ArticleInterface {

    protected $article;
    public function __construct(Model $article)
    {
        $this->article = $article;
    }

    public function byPage($page=1, $limit=10)
    {
        $result = new \StdClass;
        $result->page = $page;
        $result->limit = $limit;
        $result->totalItems = 0;
        $result->items = array();

        $query = $this->article->orderBy('created_at', 'desc');

        $articles = $query->skip( $limit * ($page-1) )
                        ->take($limit)
                        ->get();

        $result->totalItems = $this->totalArticles($all);
        $result->items = $articles->all();

        return $result;
    }
}

and a controller action:

    public function home()
    {
        $page = Input::get('page', 1);
        $perPage = 3;
        $pagiData = $this->article->byPage($page, $perPage);

        $articles = Paginator::make($pagiData->items, $pagiData->totalItems, $perPage);

        $this->layout->content = View::make('home')->with('articles', $articles);
    }
Last updated 3 years ago.
0

You need to define what the mock should return.

$mock->shouldReceive('byPage')->once()->andReturn(...)

Last updated 3 years ago.
0

Thank you anlutro,

So I have to create 2 new article, hydrate them entirely, push on array, construct my return value with it ?

And how can I set the andReturn for

Paginator::shouldReceive('make')->once(); 
Last updated 3 years ago.
0

The same way as with $mock.

Last updated 3 years ago.
0

Yeah bu what I should return, a real Paginator instance ?

How can I instanciate one for tests ?

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Elyahou elyahou Joined 7 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.