Php 不确定我是否';我正确地使用了嘲弄

Php 不确定我是否';我正确地使用了嘲弄,php,phpunit,mockery,Php,Phpunit,Mockery,我第一次尝试模仿/模仿,我不确定下面的测试是否真的涉及到我的代码,或者只是测试我制作的模仿?此外,我意识到这段代码并不适合存储库模式,尽管它的名称是这样的。。我会努力的 班级: <?php namespace Acme\Cart\Repositories; class EloquentCartRepository{ protected $model_name = 'CartModel'; protected $model; public function __co

我第一次尝试模仿/模仿,我不确定下面的测试是否真的涉及到我的代码,或者只是测试我制作的模仿?此外,我意识到这段代码并不适合存储库模式,尽管它的名称是这样的。。我会努力的

班级:

<?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;
    }
}

这是测试我的班级的正确方法吗?或者这是对mocky/mocking的错误使用?

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

在编程中,通常处理两种类型的方法:命令和查询。查询可以获取一些值,执行一些逻辑并返回一个值。命令可以获取一些值,与外部源(例如数据库)通信,但不返回任何内容。查询应该是存根的(这意味着,它们不应该对调用的数量做任何预期,而应该只对它返回的内容做任何预期),并且命令应该是模拟的(这意味着,它们应该只包含对调用的数量(以及是否)的预期)

->save()
方法是一个命令:它与数据库通信。所以它应该被嘲笑。要模拟对象,请使用mocky的
->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);
}
尽管名字叫Mockry,但默认情况下它是一个存根框架。除非您明确指定像
->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);
}