【问题标题】:Testing Eloquent Save method from a repository从存储库测试 Eloquent Save 方法
【发布时间】:2013-11-19 07:27:57
【问题描述】:

给定一个看起来像这样的雄辩的回购。

 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]);
    }
}

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

“这个模拟对象上不存在方法::fill()”

鉴于此设置,有什么方法可以让该测试通过?

【问题讨论】:

    标签: unit-testing phpunit laravel-4 eloquent


    【解决方案1】:

    这是我想出的:

    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" );
        }
    

    这看起来很老套,但至少我可以用这种方法测试对我来说重要的东西。非常欢迎对此进行任何改进。

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2016-07-28
      相关资源
      最近更新 更多