【问题标题】:Error when testing Laravel controller with mockery: Call to a member function fetchMock() on a non-object使用 mockery 测试 Laravel 控制器时出错:在非对象上调用成员函数 fetchMock()
【发布时间】:2014-08-02 00:06:52
【问题描述】:

在 Laravel 4.2 中使用控制器的 Mockery (dev-master) 进行 PHPUnit 测试时收到以下错误:

致命错误:在第 129 行的 \laravel\vendor\mockery\mockery\library\Mockery.php 中的非对象上调用成员函数 fetchMock()

控制器和测试如下:

class UserControllerTest extends TestCase {
  public function __construct() {
    $this->mock = Mockery::mock('Eloquent', 'User');
  }
  function tearDown() {
    Mockery::close();
  }
  public function testIndex() {
    $this->mock
      ->shouldReceive('all')
      ->once()
      ->andReturn('foo');
    $this->app->instance('User', $this->mock);
    $response = $this->action('GET', 'UserController@index');
    //other stuff
  }
}

class UserController extends \BaseController {
  protected $user;
  public function __construct(User $user) {
    $this->user = $user;
  }
  public function index() {
    $users = $this->user->all();
    return View::make('users.index', ['users' => $users]);
  }
  //other stuff
}

这个测试在没有 Mockery 的情况下可以正常工作(即不执行 $this->app->instance('User', $this->mock);

fetchMock 函数在执行时引发错误 return self::$_container->fetchMock($name);

以下是 fetchMock 失败时在调试器中可见的值:

是什么导致了这个错误?

【问题讨论】:

    标签: laravel mockery


    【解决方案1】:

    使用此方法替换__construct 方法并重试:

    public function setUp() {
        parent::setUp();
        $this->mock = Mockery::mock('Eloquent', 'User');
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 2014-02-21
      • 1970-01-01
      • 2014-05-11
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多