Cannot set public property on Mockery mock object
Asked Answered
N

1

6

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?

Nicki answered 1/6, 2015 at 9:17 Comment(2)
What version of PHPUnit do you use?Grillroom
Did you tested it with the function set() and andSet()?Inmost
A
2

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:

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);
Agranulocytosis answered 17/2, 2016 at 21:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.