2017-12-05 8 views
0

모의로 Carbon::now()Transaction::where... (laravel의 웅변 모델)을 모의하고 싶습니다. 가능한가? 코드가 의존성 주입하지 않고 쓸 때 나는이 작업을 수행 할 수있는 방법 어떤 생각이없는정적 방법을 사용하는 phpunit 테스트 방법

class SomeClass 
{ 
    public function getLatest() 
    { 
     $cacheTime = Carbon::now(); 

     if ($cacheTime > 'xxxx') { 
      return 'abcdefgh'; 
     } 

     return Transaction::where('base', '=', 'asas') 
      ->where('target', '=', 'bbbb') 
      ->orderByDesc('created_at') 
      ->first(); 
    } 
} 
+0

'Transaction' 라이브러리의 어떤 종류 :이 링크를 체크 아웃? 링크 또는 전체 네임 스페이스를 제공하십시오. – zstate

+0

App \ Transaction (Larave 모델). SomeClass는 서비스 App \ Services \ SomeClass입니다. –

답변

1

쉽게 Carbon을 조롱 할 수 있습니다 : 당신의 단위 테스트에 따라서

http://carbon.nesbot.com/docs/#api-testing

$knownDate = Carbon::create(2001, 5, 21, 12);   // create testing date 
Carbon::setTestNow($knownDate);      // set the mock (of course this could be a real mock object) 
echo Carbon::now();         // 2001-05-21 12:00:00 

단지 함수 호출 전에 Carbon::setTestNow($knownDate);으로 호출하십시오. 그런 뭔가 :

public function testGetLatest() 
{ 
    $knownDate = Carbon::create(2001, 5, 21, 12);   // create testing date 
    Carbon::setTestNow($knownDate); 
    $someClass = new SomeClass; 

    $result = $someClass->getLatest(); 

    ... 
} 

난 당신이 코드에서 Transaction::where을 조롱 할 수 있다고 생각하지 않고 그 일의 용도로는 사용되지 않습니다. whereorderByDesc은 검색어를 설정하는 기능입니다. first 함수는 실제로 Transaction 개체를 반환합니다. first 함수를 모방하거나 스텁 할 수 있다고해도 getLatest 함수가 생성 한 모의 객체를 반환한다고 테스트하므로 쓸모가 없습니다.

실제로 이것은 통합 테스트의 좋은 예이며 Laravel은이를 쉽게 만들기위한 다양한 유용한 도구를 제공합니다.

https://laravel.com/docs/5.5/database-testing#writing-factories

+0

어쩌면 당신은 웅변 모델을 모의 만들 수있는 아이디어가 있습니까? 시도하고있는 im ... 그리고 어떤 효과가 아니라도 –

+0

나의 갱신되었던 대답을 보라. – zstate