phpunit error when testing an implementation with injected dependencies

梦想与她 提交于 2020-01-06 06:53:23

问题


I am trying to set up a phpunit test on a class I have built called EloquentListing which implements an interface called ListingInterface. The constructor for the EloquentListing model requires an Eloquent Model to be injected. As such I am using a service provider to bind the implementation to the interface and inject the model called RepoServiceProvider. However, I am getting the following error when I run phpunit:

.PHP Fatal error: Cannot instantiate interface PlaneSaleing\Repo\Listing\ListingInterface in /home/cabox/workspace/app/tests/PlaneSaleing/Repo/Listing/EloquentListingTest.php on line 11

My code is as follows:

ListingInterface.php

<?php

namespace PlaneSaleing\Repo\Listing;

interface ListingInterface {

    public function byPage($page=1, $limit=10);
}

EloquentListing.php

<?php

namespace PlaneSaleing\Repo\Listing;

use Illuminate\Database\Eloquent\Model;

class EloquentListing implements ListingInterface {

    protected $advert;

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

    /**
     * Get paginated listings
     *
     * @param int  Current page
     * @param int Number of listings per page
     * @return StdClass object with $items and $totalItems for pagination
     */
    public function byPage($page=1, $limit=10)
    {

        $result = new \StdClass;
        $result->page = $page;
        $result->limit = $limit;
        $result->totalItems = 0;
        $result->items = array();

        $listings = $this->advert
                         ->orderBy('created_at')
                         ->skip( $limit * ($page-1) )
                         ->take($limit)
                         ->get();

        // Create object to return data useful for pagination
        $result->items = $listings->all();
        $result->totalItems = $this->totalArticles;

        return data;

    }

}

RepoServiceProvider.php

<?php

namespace PlaneSaleing\Repo;

use Illuminate\Support\ServiceProvider;
use PlaneSaleing\Repo\Listing\EloquentListing as Listing;
use Advert;

class RepoServiceProvider extends ServiceProvider {

    public function register()
    {

      $this->app->bind('PlaneSaleing\Repo\Listing\ListingInterface', function($app) {
        return new Listing(new Advert);
      } );

    }

}

EloquentListingTest.php

<?php

use PlaneSaleing\Repo\Listing\EloquentListing as Listing;

class EloquentListingTest extends TestCase {

    public function testListingByPage()
    {

        // Given
        $listing = new Listing(Mockery::mock('Advert'));
        $result = $listing->byPage();

        // When


        // Then
        $this->assertTrue($result == 10);
    }

}

来源:https://stackoverflow.com/questions/31876908/phpunit-error-when-testing-an-implementation-with-injected-dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!