Skip to content

Instantly share code, notes, and snippets.

@colindecarlo
Created May 23, 2012 03:11
Show Gist options
  • Save colindecarlo/2773053 to your computer and use it in GitHub Desktop.
Save colindecarlo/2773053 to your computer and use it in GitHub Desktop.
testing protected methods using ReflectionMethod
<?php
// interesting bits
public function test_protected_persist_directly_with_reflection_success()
{
$filePersister = new File($_FILES, $this->logger);
$reflectedPersist = new \ReflectionMethod($filePersister, '_persist');
$reflectedPersist->setAccessible(true);
$reflectedPersist->invoke($filePersister);
$persistedLocation = \PHPUnit_Framework_Assert::readAttribute($filePersister, '_location');
$this->assertRegExp('/UL-/', $persistedLocation);
$this->assertTrue(file_exists($persistedLocation));
$this->assertEquals("Hello World\n", file_get_contents($persistedLocation));
}
public function test_protected_persist_directly_with_refelection_failure()
{
$filePersisterMock = $this->getMockBuilder('GPUG\Examples\Persister\File')
->setConstructorArgs(array($_FILES, $this->logger))
->setMethods(array('_moveUploadedFile'))
->getMock();
$filePersisterMock->expects($this->once())
->method('_moveUploadedFile')
->will($this->returnValue(false));
$reflectedPersist = new \ReflectionMethod($filePersisterMock, '_persist');
$reflectedPersist->setAccessible(true);
try {
$reflectedPersist->invoke($filePersisterMock);
} catch (\Exception $e) {
$this->assertNull(\PHPUnit_Framework_Assert::readAttribute($filePersisterMock, '_location'));
$this->assertEquals('error moving uploaded file', $e->getMessage());
return;
}
$this->fail('Expected exception was not thrown in test_protected_persist_directly_with_reflection_failure');
}
// interesting bits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment