php larval 胖模型,php-Laravel控制器单元测试模拟模型未调用

我正在尝试测试控制器动作.该操作应在模型上调用函数,并返回模型.在测试中,我模拟了模型,并将其绑定到IoC容器.我有通过其构造函数注入到控制器的依赖项.但是不知何故,没有找到并调用该模拟,而是调用了该模型的实时版本. (我知道,正在生成日志.)

首先,我的单元测试.创建模拟,告诉它期望一个函数,将其添加到IoC容器,调用路由.

public function testHash(){

$hash = Mockery::mock('HashLogin');

$hash->shouldReceive('checkHash')->once();

$this->app->instance('HashLogin', $hash);

$this->call('GET', 'login/hash/c3e144adfe8133343b37d0d95f987d87b2d87a24');

}

其次,在我的控制器构造函数中注入依赖项.

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('/');}

});

}

然后是我的控制器方法.

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('/');

}

该controller方法已被正确调用,但似乎没有看到我的Mock,因此正在调用实际模型的函数.这导致模拟的期望失败,并且导致对DB的检查是不希望的.

在另一个测试中,我也遇到了同样的问题,尽管该测试使用的是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');

}

控制器方法:

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('/');

}

我收到错误:

Mockery\Exception\InvalidCountException: Method get("username") from Mockery_5_Illuminate_Http_Request should be called exactly 1 times but called 0 times."

同样,我知道该方法已正确调用,似乎只是没有使用模拟程序.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值