2016-09-06 1 views
1

내 클래스의 생성자에서 다른 클래스를 주입한다고 말합니다. 내 방법 중 하나에서 나의 반품은 그 반에 달려있다. 어떻게 그 수익을 테스트 할 수 있습니까? Phpunit 테스트 생성자에 삽입 된 다른 클래스를 사용하는 메서드

class MyClass { 

    protected $directoryThatIWant; 

    public function __construct(
     \AnotherClass $directoryThatIWant 
    ) 
    { 
     $this->directoryThatIWant = $directoryThatIWant; 
    } 

    public function getVarFolderPath() 
    { 
     return $this->directoryThatIWant->getPath('var'); 
    } 
} 

내 테스트 클래스 :

class MyClassTest extends \PHPUnit_Framework_TestCase 
{ 
    const PATH = 'my/path/that/I/want'; 

    protected $myClass; 

    protected function setUp() 
    { 
     $directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class) 
      ->disableOriginalConstructor() 
      ->getMock(); 
     $this->myClass = new myClass(
      $directoryThatIWantMock 
     ); 
    } 

    public function testGetVarFolderPath() 
    { 
     $this->assertEquals(self::PATH, $this->myClass->getVarFolderPath()); 
    } 
} 

모의 객체에서 메소드가 null를 돌려, 그래서 내가 $this->myClass->getVarFolderPath() 내가 원하는 값을 반환하도록 할 수 있습니다 방법을 확실 해요.

감사합니다.

답변

1

테스트 이중 phpunit 가이드 here에 설명 된대로 조롱 된 객체의 동작 만 정의하면됩니다.

는 예를 들어 당신은 다음과 같이 설정 방법을 변경할 수 있습니다

protected function setUp() 
{ 
    $directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class) 
     ->disableOriginalConstructor() 
     ->getMock(); 

    $directoryThatIWantMock->expects($this->once()) 
     ->method('getPath')->with('var') 
     ->willReturn('my/path/that/I/want'); 


    $this->myClass = new myClass(
     $directoryThatIWantMock 
    ); 
} 

희망이 도움

+0

감사합니다. willReturn (...)으로 예제를 보았지만 혼란 스럽습니다. 그거 아무것도 제대로 테스트하지 않니? 내 메소드 getVarFolderPath가 내가 원하는 것을 반환하는지 확신 할 수 없다. –

+0

조롱 된 객체 생성 된 메소드는 메소드가 한 번만 호출된다 (한 번 예상 됨). 그런 다음 실제 클래스가 객체를 올바르게 사용할 것임을 주장하고 잘 전달한다. . 이제 테스트가 잘됩니까? 또는 당신은 약간의 오류/잘못된 expection 있어요? – Matteo

+0

예, 이처럼 작동하지만 여기서는'$ this-> directoryThatIWant-> getPath ('var')'의 출력을 실제로 테스트하지 않습니다. 호스팅 회사에서 종종 var 폴더의 절대 경로가 변경되어 미묘한 오류가 발생하기 때문에이 테스트를 수행하고 있습니다. 내 이해에서'willReturn()'은 단지 당신이 원하는 것에 하드 코드를 사용하는 것이지 그렇지 않은가? '\ AnotherClass'가 getPath 메소드로 수행하는 작업을 실제로 수행하지 않습니다. –

관련 문제