我正在尝试学习UnitTest如何在laravel上工作。我理解如何测试控制器和模型。我不明白的是如何测试我自己的课程。
我们举个例子说:
我在app/core/chat/chat.php
创建了一个名为Chat的课程。在这种情况下,我想测试我的第一个方法load()
。如何告诉班级ChatTest
我想测试该方法?
我尝试在我的方法上实例化该类传递模拟接口(在IoC上绑定)并说当前类应该加载一次加载,但是它给出了一个错误,即方法加载应该被调用一次但是它被调用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;
}
}
}
Class ChatTest
<?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.
}
}
答案 0 :(得分:1)
问题是你需要在Mockery实例中调用 shouldReceive ,那些在Chat类中调用但不属于该类的方法,所以当你测试Chat类时,你不依赖于其他类别的回复。在这种情况下这样的事情(不是一个完全正常的代码,但希望能给你一些我在这种情况下会做的事情):
$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());