문제

Say I have the following class:

class Document
{
  private file;

  public function setFile(UploadedFile $file)
  {
    $this->file = $file;
  }

  public function getExt()
  {
    return $this->file->guessExtension();
  }
}

I'd like to test the getExt() method. I tried to set up the test as follows:

$file = $this->getMock('UploadedFile');

$file->expects($this->at(0))
  ->method('guessExtension')
  ->will($this->returnValue('png'));

$doc = new Document();
$doc->setFile($file);
...

However, it is giving me error saying that setFile() is expecting an instance of UploadedFile and the mock object is found instead. Can anyone shed some light on how to test this kind of scenario? I am a beginner when it comes to testing with mocks and stubs.

Thanks!

도움이 되었습니까?

해결책

Thanks to fab's comment. I made the following change and got it working,

$file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
        ->disableOriginalConstructor()
        ->getMock();

다른 팁

As of PHP 5.5.16 Chieh solution can't be used anymore. See reference.

A possibile solution is creating a temporary dummy file in /tmp with setUp()/tearDown() and pass it tot he constructor. Then we mocked the required methods to return what needed.

Note: UploadedFile will require you to pass two parameters

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top