2

我对测试控制器非常陌生,并且遇到了方法()的问题。我相信我要么在测试中遗漏了一些东西,要么我的控制器/存储库设计不正确。

我正在编写的应用程序基本上是那些安全的“一次性”工具之一。在您创建笔记的地方,系统会为您提供一个 URL,一旦检索到该 URL,该笔记就会被删除。我实际上已经编写了应用程序,但我要回去编写练习测试(我知道这是倒退的)。

我的控制器:

use OneTimeNote\Repositories\NoteRepositoryInterface as Note;

class NoteController extends \Controller {

protected $note;

public function __construct(Note $note)
{
    $this->note = $note;
}

public function getNote($url_id, $key)
{
    $note = $this->note->find($url_id, $key);

    if (!$note) {
        return \Response::json(array('message' => 'Note not found'), 404);
    }

    $this->note->delete($note->id);

    return \Response::json($note);
}
...

我已经将我的 Note 接口注入到我的控制器中,一切都很好。

我的测试

use \Mockery as M;

class OneTimeNoteTest extends TestCase {

    public function setUp()
    {
        parent::setUp();

        $this->mock = $this->mock('OneTimeNote\Repositories\EloquentNoteRepository');
    }

    public function mock($class)
    {
        $mock = M::mock($class);

        $this->app->instance($class, $mock);

        return $mock;
    }

    public function testShouldReturnNoteObj()
    {
        // Should Return Note
        $this->mock->shouldReceive('find')->once()->andReturn('test');
        $note = $this->call('GET', '/note/1234567890abcdefg/1234567890abcdefg');
        $this->assertEquals('test', $note->getContent());
    }

}
...

我得到的错误

1) OneTimeNoteTest::testShouldReturnNoteObj
ErrorException: Trying to get property of non-object

/Users/andrew/laravel/app/OneTimeNote/Controllers/NoteController.php:24

第 24 行是指在我的控制器中找到的这一行:

$this->note->delete($note->id);

基本上我的抽象存储库方法 delete() 显然找不到 $note->id 因为它在测试环境中确实不存在。我应该在测试中创建一个注释并尝试实际删除它吗?或者那应该是一个模型测试?如您所见,我需要帮助,谢谢!

-----更新-----

我试图存根存储库以返回一个 Note 对象,正如 Dave Marshall 在他的回答中提到的那样,但是我现在收到另一个错误。

1) OneTimeNoteTest::testShouldReturnNoteObj
BadMethodCallException: Method     Mockery_0_OneTimeNote_Repositories_EloquentNoteRepository::delete() does not exist on this mock object

我的存储库中确实有一个 delete() 方法,当我在浏览器中测试我的路由时,我知道它正在工作。

public function delete($id)
{
    Note::find($id)->delete();
}
4

2 回答 2

3

您正在存根注释存储库以返回一个字符串,然后 PHP 试图检索字符串的 id 属性,因此出现错误。

您应该存根存储库以返回一个 Note 对象,例如:

$this->mock->shouldReceive('find')->once()->andReturn(new Note());
于 2014-02-13T20:41:16.820 回答
1

基于戴夫的回答,我能够弄清楚我的问题是什么。我不是在嘲笑 delete() 方法。我不明白需要在我的控制器中模拟将被调用的每个单独的方法。

我刚刚添加了这一行:

$mock->shouldReceive('delete')->once()->andReturnNull();

由于我的删除方法只是在找到笔记后将其删除,因此我继续对其进行了模拟,但将其设置为返回 null。

于 2014-02-14T18:23:55.373 回答