从存储库测试Eloquent Save方法

时间:2013-11-07 15:14:58

标签: unit-testing phpunit laravel-4 eloquent

鉴于一个雄辩的回购看起来像那样。

 class PinRepo {
        protected $pinModel; 

        public function __construct( Model $pinModel )
        {
            $this->pinModel = $pinModel;
        }
        public function addPinToProject( $page_id, $inputs )
        {
            $pin = new $this->pinModel();
            $pin->fill($inputs);
            $pin->save();
            return $pin;
        }
    }

我的第一次尝试是:

class PinRepoTest extends TestCase {

    public function setUp()
    {
        parent::setUp();
        $this->modelMock = Mockery::mock( 'Pin' );
        $this->pinRepo = PinRepo( $this->modelMock );
    }

    public function testAddPinToPage() 
    {       
        $this->modelMock
            ->shouldReceive('fill')->with(["project_page_id"=>1])
            ->once()
            ->andReturn(Mockery::self())
            ->shouldReceive('save')
            ->once();
        $this->pinRepo->addPinToProject( 2, ["project_page_id"=>1]);
    }
}

但是我得到了这个错误(哪种有意义)

  

此模拟对象“

上不存在”Method :: fill()

鉴于此设置,有没有办法让测试通过?

1 个答案:

答案 0 :(得分:0)

以下是我的想法:

class modelStub extends Illuminate\Database\Eloquent\Model {

    static $methodCalls = [];

    public function fill(array $attributes)
    {
        self::$methodCalls['fill'] = TRUE;
        return $this;
    }
    public function save(array $options = array())
    {
        self::$methodCalls['save'] = TRUE;
        //dd($this);
        return $this;
    }

    public function __set($name, $value)
    {
        //dd($name, $value);
        static::$$name = $value;
        return $this;
    }
}


class pageModelStub extends modelStub {
    static $project_guid = false;
}

    public function testAddPageToProject()
    {
        $modelStub = new pageModelStub;
        $this->pageRepo = new \Nota\Repos\PageRepo( $modelStub );
        $this->pageRepo->addPageToProject('project_guid', ['fds']);
        $this->assertTrue( $modelStub::$methodCalls['fill'] );
        $this->assertTrue( $modelStub::$methodCalls['save'] );
        $this->assertEquals( $modelStub::$project_guid, "project_guid" );
    }

看起来很酷,但至少我可以用这种方法测试对我来说有什么问题。对此的任何改进都是非常受欢迎的。