2014-02-19 3 views
0

UnitTest가 laravel에서 어떻게 작동하는지 배우려고합니다. 컨트롤러와 모델을 테스트하는 방법을 알고 있습니다. 내가 이해하지 못하는 것은 내 자신의 수업을 시험하는 방법이다.UnitTest on laravel에 대한 이해 4

것은의 예로 들어 가정 해 봅시다 :

나는 app/core/chat/chat.php에서 클래스라는 채팅을했다. 이 경우 나는 첫 번째 방법을 시험해보고 싶다 load(). 어떻게하면 그 방법을 테스트하고 싶은지 ChatTest 클래스에 알릴 수 있습니까?

나는 모의 인터페이스 (IoC에 묶여 있음)를 전달하는 클래스에 인스턴스를 만들려고했는데 현재 클래스는 shouldReceive로드를 한 번 수행한다고했지만 메소드로드가 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; 
     } 
    } 
} 

클래스 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

: // laravel-testing.com/books/laravel-testing-decoded), 당신은 그것을 얻고 싶을지도 모르지만, 단위 테스트 Laravel 프로젝트에 대한 방법을 다룹니다. – Rooneyl

+0

책을 주셔서 감사합니다. 가능한 한 빨리 읽어 보도록하겠습니다. 그 동안 나는 여전히 답답함에 시달린다. – Fabrizio

답변

1

문제는 당신이 조롱의 경우에 shouldReceive를 호출 할 필요가있다, 채팅 클래스 내에서 호출되어 그 방법 그 클래스의 일부가 아니므로 채팅 클래스를 테스트 할 때 다른 클래스 응답에 의존하지 않습니다. (당신에게 내가이 경우에 어떻게 할 것인지의 힌트를 줄 수 있도록 노력하겠습니다하지만 완벽하게 작동 코드)이 같은이 경우 뭔가 :

제프리 웨이 LARAVEL TESTING 해독 (HTTP이라는 책을 썼다
$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()); 
+0

대단히 감사합니다! 너무 많이 귀하의 예제를 이해 주셔서 감사합니다,하지만 그것은 단지 같은 클래스에 속하는 메서드를 exist() 테스트 할 수있는 방법에 대한 명확하지 않습니다 :) – Fabrizio