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