2014-03-25 227 views
0

我第一次嘲笑嘲笑/嘲笑,我不确定下面的测试是否真的触摸我的代码,或者只是测试我做出的模拟?另外,我意识到这个代码并不适合存储库模式,尽管它的名字就是这样的。我将继续努力。不确定我是否正确使用嘲讽

类:

<?php namespace Acme\Cart\Repositories; 

class EloquentCartRepository{ 
    protected $model_name = 'CartModel'; 
    protected $model; 
    public function __construct($model = null) 
    { 
     $this->model = is_null($model) ? new $this->model_name : $model; 
    } 

    public function create_visitor_cart($session_id,$type = 'main'){ 
     return $this->create('visitor',$session_id,$type); 
    } 
    protected function create($user_type = null,$user_identifier = null,$type = 'main') 
    { 
     if(is_null($user_identifier)) throw new \Exception('Cannot create create cart, missing user identifier'); 
     if(is_null($user_type)) throw new \Exception('Cannot create create cart, missing user type'); 
     if($user_type == 'visitor') 
     { 
      $this->model->user_session_id = $user_identifier; 
     } 
     else 
     { 
      $this->model->user_id = $user_identifier; 
     } 
     $this->model->type = $type; 
     $this->model->save(); 
     return $this->model; 
    } 
} 

而且我的测试:

/** @test */ 
public function create_visitor_cart_calls_internal() 
{ 
    $model = m::mock('Models\CartModel'); 
    $model->shouldReceive('user_session_id')->with('sess123'); 
    $model->shouldReceive('type')->with('main'); 
    $model->shouldReceive('save')->andReturn($model); 

    $repository = new EloquentCartRepository($model); 
    $created_model = $repository->create_visitor_cart('sess123','main'); 
    $this->assertEquals('sess123',$created_model->user_session_id); 
    $this->assertEquals('main',$created_model->type); 
} 

这是测试我的课有道?或者这是不正确的使用嘲笑/嘲弄?

回答

0

而不是测试返回的内容,你应该测试它被保存。那意味着,那->save()运行。您在->save()上设定的期望值为$model->shouldReceive('save')->andReturn($model);。这没有意义,因为代码不使用返回值->save()

在编程中,通常处理两种类型的方法:命令和查询。查询可以获得一些价值,做一些逻辑并返回一个值。命令可以获得一些值,与外部源(例如数据库)通信并不返回任何内容。查询应该被扼杀(这意味着,它们不应该对它被调用的多少有任何期望,而只是针对它返回的内容)和命令应该被嘲弄(这意味着它们应该只包含期望多少(如果)它叫做)。

->save()方法是一个命令:它与数据库进行通信。所以它应该被嘲笑。要嘲笑对象,请使用Mockery的->once()方法。它设置一个期望,它应该被称为一个时间:

/** @test */ 
public function create_visitor_cart_calls_internal() 
{ 
    $model = m::mock('Models\CartModel'); 
    $model->shouldReceive('save')->once(); 

    $repository = new EloquentCartRepository($model); 
    $created_model = $repository->create_visitor_cart('sess123','main'); 
    $this->assertEquals('sess123',$created_model->user_session_id); 
    $this->assertEquals('main',$created_model->type); 
} 

尽管它的名字,嘲弄缺省为存根框架。它不验证的方法被调用,除非你明确的指定一个像->once()

欲了解更多信息的期望,请参阅文档:https://github.com/padraic/mockery-docs/blob/master/reference/expectations.rst