Php 理解laravel 4的单元测试

Php 理解laravel 4的单元测试,php,unit-testing,mocking,laravel-4,Php,Unit Testing,Mocking,Laravel 4,我正在努力学习单元测试如何在laravel上工作。我了解如何测试控制器和模型。我不懂的是如何测试我自己的班级 举个例子: 我在app/core/Chat/Chat.php中创建了一个名为Chat的类。在这种情况下,我想测试我的第一个方法load()。如何告诉类chatterst我要测试该方法 我试图在我的方法上对该类进行实例,将模拟接口(绑定在IoC上)传递给它,并说当前类应该接收一次加载,但它给我的错误是,该方法加载应该调用1次,但它调用了0次。我哪里出错了 课堂聊天 <?php nam

我正在努力学习单元测试如何在laravel上工作。我了解如何测试控制器和模型。我不懂的是如何测试我自己的班级

举个例子:

我在
app/core/Chat/Chat.php中创建了一个名为Chat的类。在这种情况下,我想测试我的第一个方法
load()
。如何告诉类
chatterst
我要测试该方法

我试图在我的方法上对该类进行实例,将模拟接口(绑定在IoC上)传递给它,并说当前类应该接收一次加载,但它给我的错误是,该方法加载应该调用1次,但它调用了0次。我哪里出错了

课堂聊天

<?php namespace Core\Chat\Chat;

use Core\Chat\Chat\Models\MessageInterface;
use Core\Chat\Chat\Models\ConversationInterface;

Class Chat { 
    function __construct(ConversationInterface $conversation,MessageInterface $message) { 
        $this->conversation = $conversation;
        $this->message = $message;
        $this->app = app();
    }

    /**
    * Get Messages of a conversation, on the current user
    *
    * @param $user_id | id user id
    * @return Bool | true | False
    */

    public function load($user_id) {
        $conversation = $this->exist( $user_id, $this->app['sentry']->getUser()->id );
        if ($conversation) {
            $messages = $this->conversation->loadConversation($conversation->id);    
            $this->status = "success";
            $this->response = $messages;
            return true;
        } else {
            $this->status = "error";
            $this->response = "no conversation";
            return false;
        }
    }
}
<?php

use \Mockery;

/**
 * Class ChatTest
 */
class ChatTest extends TestCase { 
    public function tearDown()
    {
        Mockery::close();
    }

    public function test_load_messages_conversation() {    
        $convInterface = Mockery::mock('Core\Chat\Chat\Models\ConversationInterface');
        $messInterface = Mockery::mock('Core\Chat\Chat\Models\MessageInterface');
        $chat = new Chat($convInterface,$messInterface);
        $chat->shouldReceive('load')->once();
        // error it should be called 1 time but it called 0 times.              
    }
}

问题在于,您需要在mockry实例中调用shouldReceive,这些方法在Chat类中调用,但不属于该类,因此在测试Chat类时,您不需要依赖其他类的响应。在本例中,类似这样的内容(不是一个完全有效的代码,但希望能给您一个提示,说明我在本例中会做什么):


Jeffery Way写了一本名为《LARAVEL TESTING DECODED()》的书,你可能想知道,它介绍了如何对LARAVEL项目进行单元测试。感谢这本书,我建议尽快阅读。在这个时候,我对答案仍然很认真。非常感谢!我非常感谢您的示例,我理解了方法,但不清楚如何测试属于同一类的exist()方法:)
$sentryMock->shouldReceive('getUser')->andReturn(new User);
$convMock->shouldReceive('loadConversation')->andReturn(new MessageInterface);
$chat = new Chat(); //should be working with IoC bindings
$this->assertTrue($chat->load());