phpunit – 用find()模拟Eloquent模型

我正试图用Mockery模拟Eloquent模型.模型正在Controller中注入
__construct(Post $model){$this->model=$model}

现在我在控制器中调用find()函数

$post = $this->model->find($id);

这里是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));
      }
    }

运行PHPUnit给我错误

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

这显然是因为find()被声明为静态函数.现在,代码可以正常运行,因此如何在不失败的情况下成功模拟Eloquent模型.由于我们依赖于依赖注入,我必须非静态地调用find(),否则我可以只做Post :: find().

我想出的一个解决方案是在BaseModel中创建一个非静态的find()替换

public function nsFind($id,$columns = array('*'))
{
  return self::find($id,$columns);
}

但这是一个巨大的痛苦,因为功能必须有不同的名称

我做错了什么或你有更好的想法吗?

嘲弄雄辩的模型是一件非常棘手的事情.本书对此进行了介绍,但我特别注意到这是一个止损.最好使用存储库.

但是,要回答您的问题,问题是您没有在构造函数中执行模拟.这是让它发挥作用的唯一方法.它不理想,我不推荐它.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...