mockery-> shouldReceive()传递的时候不应该?

Mar*_*ark 5 php phpunit laravel mockery laravel-4

我正在使用phpunit和mockery学习laravel中的单元测试.我目前正在尝试测试UsersController :: store().

我正在嘲笑用户模型并使用它来测试索引方法,这似乎有效.当我取出$ this-> user-> all()时,测试失败,当它进入时.

在测试store方法时,我使用mock来测试用户模型是否接收到validate()一次.store方法为空,但测试通过.为了简单起见,我遗漏了班级中不相关的部分

<?php

class UsersController extends BaseController {

    public function __construct(User $user)
    {
        $this->user = $user;
    }
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = $this->user->all();

        return View::make('users.index')
        ->with('users', $users);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return View::make('users.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }

}
Run Code Online (Sandbox Code Playgroud)

UserControllerTest.php

<?php
    use Mockery as m;
class UserControllerTest extends TestCase {

    public function __construct()
    {
        $this->mock = m::mock('BaseModel', 'User');
    }

    public function tearDown()
    {
        m::close();
    }

    public function testIndex()
    {
        $this->mock
            ->shouldReceive('all')
            ->once()
            ->andReturn('All Users');
        $this->app->instance('User', $this->mock);
        $this->call('GET', 'users');
        $this->assertViewHas('users', 'All Users');
    }

    public function testCreate()
    {
        View::shouldReceive('make')->once();
        $this->call('GET', 'users/create');
        $this->assertResponseOk();
    }

    public function testStore()
    {

        $this->mock
            ->shouldReceive('validate')
            ->once()
            ->andReturn(m::mock(['passes' => 'true']));
        $this->app->instance('User', $this->mock);
        $this->call('POST', 'users');
    }


}
Run Code Online (Sandbox Code Playgroud)

Wou*_*r J 13

默认情况下,Mockery是一个存根库,而不是一个模拟库(由于它的名称而令人困惑).

这意味着->shouldReceive(...)默认情况下为"零次或多次".使用时->once(),你说它应该被称为零或一次,但不是更多.这意味着它将永远通过.

当你想断言它被调用一次时,你可以使用->atLeast()->times(1)(一次或多次)或->times(1)(恰好一次)

  • 默认情况下,“-&gt; shouldReceive(...)”等于“零次或多次”,它不会影响其他方法。“-&gt; once()”指出应该恰好一次调用它,如果不调用它,它将失败。 (2认同)

Gui*_*lla 5

要完成Woonter 的回答,您必须致电Mockery::close()

此静态调用会清理当前测试使用的 Mockery 容器,并运行您期望所需的任何验证任务。

这个答案帮助我理解了这个概念。


Bra*_*sen 1

PHPUnit_Framework_TestCase您不应该为了初始化目的而覆盖, use的构造函数setUp。另请参阅我对#15051271#17504870的回答