Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set public property on Mockery mock object

I'm trying to use Mockery to create a mock object that mimics PHP's internal ZipArchive class.

I have something like the following PHP code:

$zipMock = Mockery::mock('ZipArchive');
$zipMock->numFiles = 10;
echo 'NUMBER OF FILES: '.$zipMock->numFiles;

However, when I run it I get the following result:

NUMBER OF FILES: 0

I'd expect it to show 10, rather than 0. I can't work out why this is happening since the documentation implies that it should be possible to set public properties on mock objects directly. What am I missing?

like image 806
FixMaker Avatar asked Jun 01 '15 09:06

FixMaker


1 Answers

I can't work out why this is happening since the documentation implies that it should be possible to set public properties on mock objects directly. What am I missing?

You're missing the point that ZipArchive::$numFiles is not a standard public property. A ZipArchive is not a userland PHP class (plain old PHP object) but one from a PHP extension. That means the property is effectively read-only:

  • http://lxr.php.net/xref/PHP_5_6/ext/zip/php_zip.c#php_zip_get_num_files

So mocking with Mockery is not an option for the num-files property. But you can mock your own with that object, here with 10 files:

$file = tempnam(sys_get_temp_dir(), 'zip');

$zip = new ZipArchive;
$zip->open($file, ZipArchive::CREATE);

foreach(range(1, 10) as $num) {
    $zip->addFromString($num, "");
}

var_dump($zip->numFiles);

$zip->close();
unlink($file);
like image 189
hakre Avatar answered Sep 22 '22 14:09

hakre