我尝试用 mock 的方式在 Laravel 中测试我的 Controller 操作。我已经在这里阅读了本教程:
http://culttt.com/2013/07/15/how-to-structure-testable-controllers-in-laravel-4/
我在构造函数中使用 DI,如下所示:
public function __construct(User $user, Cartalyst\Sentry\Sentry $sentry)
{
$this->user = $user;
$this->sentry = $sentry;
...
}
我的问题是 Controller 中的以下代码:
public function getShow($id)
{
try
{
// this is a problem, because I dont know how to tell mockery, to mock the
// Userprovider
$user = $this->sentry->getUserProvider()->findById($id);
// this is not a problem for me
$this->user->all();
...
我正在尝试使用 Mockery 作为模拟框架。我的问题是如何模拟像 $this->sentry->getUserProvider() 这样的调用(Cartalyst Sentry 是一个高级授权包)。为了模拟我写的用户模型:
$this->user = Mockery::mock('Eloquent', 'User');
知道如何模拟 Userprovider 或者我应该以其他方式处理这个问题吗?我想测试我的 UserController 是否根据 id 获取用户详细信息。
最佳答案
您可以对 getUserProvider 方法进行 stub 以返回另一个 stub ,例如
$sentry = m::mock("F\Q\C\N\Sentry");
$userProvider = m::mock("F\Q\C\N\UserProvider");
$sentry->shouldReceive("getUserProvider")->andReturn($userProvider)->byDefault();
$userProvider->shouldReceive("findById")->andReturn(new User);
关于unit-testing - 使用 Mockery 进行 Laravel Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20096769/