2

Im using the ZipArchive class in my laravel 5.6 application for handling zip files. In my tests I have created a mock for the ZipArchive class as follows:

$this->zipArchiveMock = $this->createMock(ZipArchive::class);

Im able to mock methods on the ZipArchive class like follows:

$this->zipArchiveMock->expects($this->once())
            ->method('open')
            ->will($this->returnValue(true));

I want to mock a property called numFiles of the ZipArchive class. I tried doing $this->zipArchiveMock->numFiles = 2. But $this->zipArchiveMock->numFiles is always 0. How to mock a property on the ZipArchive class ?

Thank You

joes
  • 349
  • 1
  • 2
  • 10

1 Answers1

0

Ok so there are 2 options, you can either mock the public property with Mockery or mock the count() function.

$this->zipArchiveMock->set('numFiles', 2);

(I dont know if you use Mockery, but it is included in Laravel so i assumed you did) http://docs.mockery.io/en/latest/reference/public_properties.html

Or:

$this->zipArchiveMock->expects($this->once())
    ->method('count')
    ->will($this->returnValue(2));

EDIT:

You are not using Mockery but PHPunit. I can't find a way to mock properties on an object or set properties on a mock with PHPUnit. Instead i suggest you use Mockery like this:

$this->zipArchiveMock = \Mockery::mock('ZipArchive');
$this->zipArchiveMock->set('numFiles', 2);

$this->zipArchiveMock->shouldReceive('open')
        ->once()
        ->andReturn(true);

Hope this works for you.

Fjarlaegur
  • 1,395
  • 1
  • 14
  • 33
  • Thanks for the reply. Im using PHP 7.1.21 and the count() function for ZipArchive is only available in 7.2 (Reference: http://php.net/manual/en/ziparchive.count.php#123091) . So i have to use the numFiles property. I did `$this->zipArchiveMock->set('numFiles', 2);` as you suggested but then i get the error `Call to undefined method Mock_ZipArchive_90b9991f::set()` . – joes Sep 03 '18 at 14:02
  • I just figured out you are using PHPUnit mocking. And i can't find a solution to your problem with PHPUnit. The `set()` method is a Mockery method. So i updated my question to explain Mockery some more. – Fjarlaegur Sep 04 '18 at 08:11