Epi*_*lly 3 php unit-testing mockery laravel-4
我正在尝试测试控制器操作。该操作应该调用模型上的函数,返回模型。在测试中,我模拟了模型,将其绑定到 IoC 容器。我通过控制器的构造函数将依赖项注入到控制器中。然而不知何故,没有找到并调用模拟,而是调用模型的实时版本。(我可以看出,因为正在生成日志。)
首先,我的单元测试。创建模拟,告诉它需要一个函数,将其添加到 IoC 容器,调用路由。
public function testHash(){
$hash = Mockery::mock('HashLogin');
$hash->shouldReceive('checkHash')->once();
$this->app->instance('HashLogin', $hash);
$this->call('GET', 'login/hash/c3e144adfe8133343b37d0d95f987d87b2d87a24');
}
Run Code Online (Sandbox Code Playgroud)
其次,我的控制器构造函数,其中注入了依赖项。
public function __construct(User $user, HashLogin $hashlogin){
$this->user = $user;
$this->hashlogin = $hashlogin;
$this->ip_direct = array_key_exists("REMOTE_ADDR",$_SERVER) ? $_SERVER["REMOTE_ADDR"] : null;
$this->ip_elb = array_key_exists("HTTP_X_FORWARDED_FOR",$_SERVER) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : null;
$this->beforeFilter(function()
{
if(Auth::check()){return Redirect::to('/');}
});
}
Run Code Online (Sandbox Code Playgroud)
然后是我的控制器方法。
public function getHash($code){
$hash = $this->hashlogin->checkHash($code);
if(!$hash){
return $this->badLogin('Invalid Login');
}
$user = $this->user->getFromLegacy($hash->getLegacyUser());
$hash->cleanup();
$this->login($user);
return Redirect::intended('/');
}
Run Code Online (Sandbox Code Playgroud)
控制器方法被正确调用,但似乎它没有看到我的模拟,因此它正在调用实际模型的函数。这会导致模拟的期望失败,并导致对数据库的检查是不理想的。
我在另一项测试中也遇到了同样的问题,尽管这个测试使用 Laravel 内置的 Facades。
考试:
public function testLoginSuccessfulWithAuthTrue(){
Input::shouldReceive('get')->with('username')->once()->andReturn('user');
Input::shouldReceive('get')->with('password')->once()->andReturn('1234');
Auth::shouldReceive('attempt')->once()->andReturn(true);
$user = Mockery::mock('User');
$user->shouldReceive('buildRBAC')->once();
Auth::shouldReceive('user')->once()->andReturn($user);
$this->call('POST', 'login');
$this->assertRedirectedToRoute('index');
}
Run Code Online (Sandbox Code Playgroud)
控制器方法:
public function postIndex(){
$username = Input::get("username");
$pass = Input::get('password');
if(Auth::attempt(array('username' => $username, 'password' => $pass))){
Auth::user()->buildRBAC();
}else{
$user = $this->user->checkForLegacyUser($username);
if($user){
$this->login($user);
}else{
return Redirect::back()->withInput()->with('error', "Invalid credentials.");
}
}
return Redirect::intended('/');
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Mockery\Exception\InvalidCountException: Method get("username") from Mockery_5_Illuminate_Http_Request should be called exactly 1 times but called 0 times."
Run Code Online (Sandbox Code Playgroud)
再说一遍,我知道该方法正在正确调用,只是似乎没有使用模拟。
解决了。我之前曾在一个地方或另一个地方尝试过使用命名空间,但显然 和 都Mockery::mock需要app->instance()完全命名空间的名称。我在其他测试中没有出现过这个问题,所以我什至没有考虑它。我希望这对其他人有帮助,因为这个问题让我绞尽脑汁了一段时间。
相关代码已修复:
$hash = Mockery::mock('App\Models\Eloquent\HashLogin');
$this->app->instance('App\Models\Eloquent\HashLogin', $hash);
Run Code Online (Sandbox Code Playgroud)