/** * @dataProvider validateProvider */ public function testValidate($path, $isExceptionExpected, $isUserInDatabase, $isFull, $codeExists) { $ds = DIRECTORY_SEPARATOR; $data = Yaml::parse(file_get_contents($path . $ds . 'manifest.yml')); $properties['properties'] = $data['properties']; if ($isExceptionExpected) { $this->setExpectedException('Exception'); } m::getConfiguration()->allowMockingNonExistentMethods(true); //init importer $this->importer->setRootPath($path); $resolver = new Resolver($path); $this->importer->setConfiguration($resolver->resolve($data)); //objectManager $wsRepo = $this->mock('Claroline\\CoreBundle\\Repository\\WorkspaceRepository'); $this->om->shouldReceive('getRepository')->with('Claroline\\CoreBundle\\Entity\\Workspace\\Workspace')->andReturn($wsRepo); if ($codeExists) { $wsRepo->shouldReceive('findOneByCode')->once()->with($properties['properties']['code'])->andThrow('Exception'); } else { $wsRepo->shouldReceive('findOneByCode')->once()->with($properties['properties']['code'])->andReturn('ws'); } $userRepo = $this->mock('Claroline\\CoreBundle\\Repository\\UserRepository'); if ($isUserInDatabase && !$isFull) { $this->om->shouldReceive('getRepository')->andReturn($userRepo); $userRepo->shouldReceive('findOneByUsername')->andReturn('user'); } if (!$isUserInDatabase && !$isFull) { $this->om->shouldReceive('getRepository')->andReturn($userRepo); $userRepo->shouldReceive('findOneByUsername')->andThrow('Exception'); } $this->importer->validate($properties); }
public function setUp() { \Mockery::getConfiguration()->setInternalClassMethodParamMap('MongoCollection', 'save', array('&$data', '$options = array()')); $this->collection = \Mockery::mock('MongoCollection'); $this->collection->shouldReceive('ensureIndex'); $this->db = \Mockery::mock('MongoDB'); $this->db->shouldReceive('selectCollection')->andReturn($this->collection); Moa::setup($this->db); }
public function testAnonymousMockWorksWithNotAllowingMockingOfNonExistantMethods() { $before = \Mockery::getConfiguration()->mockingNonExistentMethodsAllowed(); \Mockery::getConfiguration()->allowMockingNonExistentMethods(false); $m = $this->container->mock(); $m->shouldReceive("test123")->andReturn(true); assertThat($m->test123(), equalTo(true)); \Mockery::getConfiguration()->allowMockingNonExistentMethods(true); }
public function testMockWithNotAllowingMockingOfNonExistentMethodsCanBeGivenAdditionalMethodsToMockEvenIfTheyDontExistOnClass() { \Mockery::getConfiguration()->allowMockingNonExistentMethods(false); $m = $this->container->mock('ExampleClassForTestingNonExistentMethod'); $m->shouldAllowMockingMethod('testSomeNonExistentMethod'); $m->shouldReceive("testSomeNonExistentMethod")->andReturn(true); assertThat($m->testSomeNonExistentMethod(), equalTo(true)); \Mockery::getConfiguration()->allowMockingNonExistentMethods(true); }
/** * @group resource */ public function testSearchIcon() { $icon = new \Claroline\CoreBundle\Entity\Resource\ResourceIcon(); $mimeType = 'video/mp4'; m::getConfiguration()->allowMockingNonExistentMethods(true); $this->repo->shouldReceive('findOneByMimeType')->with($mimeType)->once()->andReturn(null); $this->repo->shouldReceive('findOneByMimeType')->with('video')->once()->andReturn(null); $this->repo->shouldReceive('findOneByMimeType')->with('custom/default')->once()->andReturn($icon); $this->assertEquals($icon, $this->getManager()->searchIcon($mimeType)); }
public function testSave() { \Mockery::getConfiguration()->setInternalClassMethodParamMap('MongoCollection', 'save', array('&$data', '$options = array()')); $collection = Mockery::mock('MongoCollection')->shouldReceive('save')->with(array('key' => 'value'), array())->andReturnUsing(function (&$mongoDoc) { $mongoDoc['_id'] = 100; })->mock(); $wrappedCollection = new Moa\DomainObject\Finder($collection, 'MyModel'); $model = new MyModel(array('key' => 'value')); $wrappedCollection->save($model); $this->assertEquals(100, $model->id()); }
function Setup() { \Mockery::getConfiguration()->allowMockingNonExistentMethods(true); $this->resolver = new \Zend\View\Resolver\TemplatePathStack(); foreach ((array) $this->getTemplatePaths() as $path) { $this->resolver->addPath($path); } $this->renderer = $this->createRenderer(); $this->renderer->setResolver($this->resolver); $this->setFormHelpers(); }
public function testCanOverrideExpectedParametersOfInternalPHPClassesToPreserveRefs() { if (!class_exists('MongoCollection', false)) { $this->markTestSkipped('ext/mongo not installed'); } \Mockery::getConfiguration()->setInternalClassMethodParamMap('MongoCollection', 'insert', array('&$data', '$options')); $m = $this->container->mock('MongoCollection'); $m->shouldReceive('insert')->with(\Mockery::on(function (&$data) { $data['_id'] = 123; return true; }), \Mockery::type('array')); $data = array('a' => 1, 'b' => 2); $m->insert($data, array()); $this->assertTrue(isset($data['_id'])); $this->assertEquals(123, $data['_id']); $this->container->mockery_verify(); \Mockery::resetContainer(); }
public function testImportUsersIntoGroupAction() { vfsStream::setup('root', null, array('users.txt' => "gg,gg,gg,gg,gg,gg,gg")); $group = $this->mock('Claroline\\CoreBundle\\Entity\\Group'); $group->shouldReceive('getId')->andReturn(42); $form = $this->mock('Symfony\\Component\\Form\\Form'); $this->formFactory->shouldReceive('create')->with(FormFactory::TYPE_USER_IMPORT)->once()->andReturn($form); $form->shouldReceive('handleRequest')->with($this->request)->once(); $form->shouldReceive('isValid')->with()->once()->andReturn(true); m::getConfiguration()->allowMockingNonExistentMethods(true); $form->shouldReceive('get->getData')->andReturn(vfsStream::url('root/users.txt')); m::getConfiguration()->allowMockingNonExistentMethods(false); $users = array(array('gg', 'gg', 'gg', 'gg', 'gg', 'gg', 'gg')); $this->userManager->shouldReceive('importUsers')->once()->with($users); $this->groupManager->shouldReceive('importUsers')->once()->with($group, $users); $this->router->shouldReceive('generate')->once()->with('claro_admin_user_of_group_list', array('groupId' => 42))->andReturn('azertyuiop'); $this->assertTrue($this->getController()->importUsersIntoGroupAction($group) instanceof RedirectResponse); }
protected function _mockery_handleMethodCall($method, array $args) { $this->_mockery_getReceivedMethodCalls()->push(new \Mockery\MethodCall($method, $args)); $rm = $this->mockery_getMethod($method); if ($rm && $rm->isProtected() && !$this->_mockery_allowMockingProtectedMethods) { if ($rm->isAbstract()) { return; } try { $prototype = $rm->getPrototype(); if ($prototype->isAbstract()) { return; } } catch (\ReflectionException $re) { // noop - there is no hasPrototype method } return call_user_func_array("parent::{$method}", $args); } if (isset($this->_mockery_expectations[$method]) && !$this->_mockery_disableExpectationMatching) { $handler = $this->_mockery_expectations[$method]; try { return $handler->call($args); } catch (\Mockery\Exception\NoMatchingExpectationException $e) { if (!$this->_mockery_ignoreMissing && !$this->_mockery_deferMissing) { throw $e; } } } if (!is_null($this->_mockery_partial) && method_exists($this->_mockery_partial, $method)) { return call_user_func_array(array($this->_mockery_partial, $method), $args); } elseif ($this->_mockery_deferMissing && is_callable("parent::{$method}")) { return call_user_func_array("parent::{$method}", $args); } elseif ($method == '__toString') { // __toString is special because we force its addition to the class API regardless of the // original implementation. Thus, we should always return a string rather than honor // _mockery_ignoreMissing and break the API with an error. return sprintf("%s#%s", __CLASS__, spl_object_hash($this)); } elseif ($this->_mockery_ignoreMissing) { if (\Mockery::getConfiguration()->mockingNonExistentMethodsAllowed() || (method_exists($this->_mockery_partial, $method) || is_callable("parent::{$method}"))) { if ($this->_mockery_defaultReturnValue instanceof \Mockery\Undefined) { return call_user_func_array(array($this->_mockery_defaultReturnValue, $method), $args); } elseif (null === $this->_mockery_defaultReturnValue) { return $this->mockery_returnValueForMethod($method); } else { return $this->_mockery_defaultReturnValue; } } } $message = 'Method ' . __CLASS__ . '::' . $method . '() does not exist on this mock object'; if (!is_null($rm)) { $message = 'Received ' . __CLASS__ . '::' . $method . '(), but no expectations were specified'; } throw new \BadMethodCallException($message); }
public function tearDown() { \Mockery::getConfiguration()->allowMockingNonExistentMethods(true); $this->container->mockery_close(); }
<?php $autoloader = (require_once dirname(__DIR__) . '/vendor/autoload.php'); $autoloader->add('Swift_', __DIR__ . '/unit'); set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__DIR__) . '/lib'); \Mockery::getConfiguration()->allowMockingNonExistentMethods(false); if (is_file(__DIR__ . '/acceptance.conf.php')) { require_once __DIR__ . '/acceptance.conf.php'; } if (is_file(__DIR__ . '/smoke.conf.php')) { require_once __DIR__ . '/smoke.conf.php'; } require_once __DIR__ . '/StreamCollector.php'; require_once __DIR__ . '/IdenticalBinaryConstraint.php'; require_once __DIR__ . '/SwiftMailerTestCase.php'; require_once __DIR__ . '/SwiftMailerSmokeTestCase.php';
/** * Call allowMockingNonExistentMethods() on setUp(). * * @param bool $allow Enable/Disable to mock non existent methods. */ public function allowMockingNonExistentMethods($allow = false) { //Disable mocking of non existent methods. $config = Mock::getConfiguration(); $config->allowMockingNonExistentMethods($allow); }
protected function setUp() { m::getConfiguration()->allowMockingNonExistentMethods(false); m::getConfiguration()->allowMockingMethodsUnnecessarily(false); }
/** * @expectedException \Mockery\Exception */ public function testWetherMockWithInterfaceOnlyCanNotImplementNonExistingMethods() { \Mockery::getConfiguration()->allowMockingNonExistentMethods(false); $waterMock = \Mockery::mock('IWater'); $waterMock->shouldReceive('nonExistentMethod')->once()->andReturnNull(); \Mockery::close(); }
public static function setUpBeforeClass() { // disallow mocking of non existent methods, so when an interface changes tests will more likely fail \Mockery::getConfiguration()->allowMockingNonExistentMethods(false); }
protected function onCreate() { \Mockery::getConfiguration()->allowMockingNonExistentMethods(true); }
public function testShouldIgnoreMissingCallingNonExistentMethods() { Mockery::getConfiguration()->allowMockingNonExistentMethods(true); $mock = $this->container->mock('ClassWithMethods')->shouldIgnoreMissing(); assertThat(nullValue($mock->foo())); assertThat(nullValue($mock->bar())); assertThat(nullValue($mock->nonExistentMethod())); $mock->shouldReceive(array('foo' => 'new_foo', 'nonExistentMethod' => 'result')); $mock->shouldReceive('bar')->passthru(); assertThat($mock->foo(), equalTo('new_foo')); assertThat($mock->bar(), equalTo('bar')); assertThat($mock->nonExistentMethod(), equalTo('result')); }
/** * Sets up expectations on the members of the CompositeExpectation and * builds up any demeter chain that was passed to shouldReceive * * @param \Mockery\MockInterface $mock * @param string $arg * @param Closure $add * @return \Mockery\ExpectationDirector */ protected static function _buildDemeterChain(\Mockery\MockInterface $mock, $arg, $add) { $container = $mock->mockery_getContainer(); $names = explode('->', $arg); reset($names); if (!\Mockery::getConfiguration()->mockingNonExistentMethodsAllowed() && method_exists($mock, "mockery_getMockableMethods") && !in_array(current($names), $mock->mockery_getMockableMethods())) { throw new \Mockery\Exception('Mockery\'s configuration currently forbids mocking the method ' . current($names) . ' as it does not exist on the class or object ' . 'being mocked'); } $exp = null; $nextExp = function ($n) use($add) { return $add($n); }; while (true) { $method = array_shift($names); $exp = $mock->mockery_getExpectationsFor($method); $needNew = false; if (is_null($exp) || empty($names)) { $needNew = true; } if ($needNew) { $exp = $nextExp($method); } if (empty($names)) { break; } if ($needNew) { $mock = $container->mock('demeter_' . $method); $exp->andReturn($mock); } $nextExp = function ($n) use($mock) { return $mock->shouldReceive($n); }; } return $exp; }
public function setUp() { m::getConfiguration()->allowMockingNonExistentMethods(false); }
/** * We want to avoid constructors since class is copied to Generator.php * for inclusion on extending class definitions. * * @param \Mockery\Container $container * @param object $partialObject * @return void */ public function mockery_init(\Mockery\Container $container = null, $partialObject = null) { if (is_null($container)) { $container = new \Mockery\Container(); } $this->_mockery_container = $container; if (!is_null($partialObject)) { $this->_mockery_partial = $partialObject; } if (!\Mockery::getConfiguration()->mockingNonExistentMethodsAllowed()) { foreach ($this->mockery_getMethods() as $method) { if ($method->isPublic() && !$method->isStatic()) { $this->_mockery_mockableMethods[] = $method->getName(); } } } }
<?php use Tester\Environment; require __DIR__ . '/../vendor/autoload.php'; Environment::setup(); Mockery::getConfiguration()->allowMockingNonExistentMethods(FALSE);
/** * Generates a new mock object for this container * * I apologies in advance for this. A God Method just fits the API which * doesn't require differentiating between classes, interfaces, abstracts, * names or partials - just so long as it's something that can be mocked. * I'll refactor it one day so it's easier to follow. * * @throws Exception\RuntimeException * @throws Exception * @return \Mockery\Mock */ public function mock() { $expectationClosure = null; $quickdefs = array(); $constructorArgs = null; $blocks = array(); $args = func_get_args(); if (count($args) > 1) { $finalArg = end($args); reset($args); if (is_callable($finalArg) && is_object($finalArg)) { $expectationClosure = array_pop($args); } } $builder = new MockConfigurationBuilder(); foreach ($args as $k => $arg) { if ($arg instanceof MockConfigurationBuilder) { $builder = $arg; unset($args[$k]); } } reset($args); $builder->setParameterOverrides(\Mockery::getConfiguration()->getInternalClassMethodParamMaps()); while (count($args) > 0) { $arg = current($args); // check for multiple interfaces if (is_string($arg) && strpos($arg, ',') && !strpos($arg, ']')) { $interfaces = explode(',', str_replace(' ', '', $arg)); foreach ($interfaces as $i) { if (!interface_exists($i, true) && !class_exists($i, true)) { throw new \Mockery\Exception('Class name follows the format for defining multiple' . ' interfaces, however one or more of the interfaces' . ' do not exist or are not included, or the base class' . ' (which you may omit from the mock definition) does not exist'); } } $builder->addTargets($interfaces); array_shift($args); continue; } elseif (is_string($arg) && substr($arg, 0, 6) == 'alias:') { $name = array_shift($args); $name = str_replace('alias:', '', $name); $builder->addTarget('stdClass'); $builder->setName($name); continue; } elseif (is_string($arg) && substr($arg, 0, 9) == 'overload:') { $name = array_shift($args); $name = str_replace('overload:', '', $name); $builder->setInstanceMock(true); $builder->addTarget('stdClass'); $builder->setName($name); continue; } elseif (is_string($arg) && substr($arg, strlen($arg) - 1, 1) == ']') { $parts = explode('[', $arg); if (!class_exists($parts[0], true) && !interface_exists($parts[0], true)) { throw new \Mockery\Exception('Can only create a partial mock from' . ' an existing class or interface'); } $class = $parts[0]; $parts[1] = str_replace(' ', '', $parts[1]); $partialMethods = explode(',', strtolower(rtrim($parts[1], ']'))); $builder->addTarget($class); $builder->setWhiteListedMethods($partialMethods); array_shift($args); continue; } elseif (is_string($arg) && (class_exists($arg, true) || interface_exists($arg, true))) { $class = array_shift($args); $builder->addTarget($class); continue; } elseif (is_string($arg)) { $class = array_shift($args); $builder->addTarget($class); continue; } elseif (is_object($arg)) { $partial = array_shift($args); $builder->addTarget($partial); continue; } elseif (is_array($arg) && !empty($arg) && array_keys($arg) !== range(0, count($arg) - 1)) { // if associative array if (array_key_exists(self::BLOCKS, $arg)) { $blocks = $arg[self::BLOCKS]; } unset($arg[self::BLOCKS]); $quickdefs = array_shift($args); continue; } elseif (is_array($arg)) { $constructorArgs = array_shift($args); continue; } throw new \Mockery\Exception('Unable to parse arguments sent to ' . get_class($this) . '::mock()'); } $builder->addBlackListedMethods($blocks); if (!is_null($constructorArgs)) { $builder->addBlackListedMethod("__construct"); // we need to pass through } if (!empty($partialMethods) && $constructorArgs === null) { $constructorArgs = array(); } $config = $builder->getMockConfiguration(); $this->checkForNamedMockClashes($config); $def = $this->getGenerator()->generate($config); if (class_exists($def->getClassName(), $attemptAutoload = false)) { $rfc = new \ReflectionClass($def->getClassName()); if (!$rfc->implementsInterface("Mockery\\MockInterface")) { throw new \Mockery\Exception\RuntimeException("Could not load mock {$def->getClassName()}, class already exists"); } } $this->getLoader()->load($def); $mock = $this->_getInstance($def->getClassName(), $constructorArgs); $mock->mockery_init($this, $config->getTargetObject()); if (!empty($quickdefs)) { $mock->shouldReceive($quickdefs)->byDefault(); } if (!empty($expectationClosure)) { $expectationClosure($mock); } $this->rememberMock($mock); return $mock; }
public function testImportUsers() { $group = $this->mock('Claroline\\CoreBundle\\Entity\\Group'); $user = $this->mock('Claroline\\CoreBundle\\Entity\\User'); $manager = $this->getManager(array('addUsersToGroup')); $users = array(array('firstname1', 'lastname1', 'username1', 'password1', '*****@*****.**', 'code1'), array('firstname2', 'lastname2', 'username2', 'password2', '*****@*****.**', 'code2')); m::getConfiguration()->allowMockingNonExistentMethods(true); $this->userRepo->shouldReceive('findOneBy')->with(array('username' => 'username1', 'firstName' => 'firstname1', 'lastName' => 'lastname1'))->once()->andReturn(null); $this->userRepo->shouldReceive('findOneBy')->with(array('username' => 'username2', 'firstName' => 'firstname2', 'lastName' => 'lastname2'))->once()->andReturn($user); m::getConfiguration()->allowMockingNonExistentMethods(false); $manager->shouldReceive('addUsersToGroup')->with($group, array($user))->once(); $manager->importUsers($group, $users); }
/** * Sets up expectations on the members of the CompositeExpectation and * builds up any demeter chain that was passed to shouldReceive * * @param \Mockery\MockInterface $mock * @param string $arg * @param callable $add * @throws Mockery\Exception * @return \Mockery\ExpectationDirector */ protected static function _buildDemeterChain(\Mockery\MockInterface $mock, $arg, $add) { /** @var Mockery\Container $container */ $container = $mock->mockery_getContainer(); $methodNames = explode('->', $arg); reset($methodNames); if (!\Mockery::getConfiguration()->mockingNonExistentMethodsAllowed() && !$mock->mockery_isAnonymous() && !in_array(current($methodNames), $mock->mockery_getMockableMethods())) { throw new \Mockery\Exception('Mockery\'s configuration currently forbids mocking the method ' . current($methodNames) . ' as it does not exist on the class or object ' . 'being mocked'); } /** @var ExpectationInterface|null $exp */ $exp = null; /** @var Callable $nextExp */ $nextExp = function ($method) use($add) { return $add($method); }; while (true) { $method = array_shift($methodNames); $exp = $mock->mockery_getExpectationsFor($method); if (is_null($exp) || self::noMoreElementsInChain($methodNames)) { $exp = $nextExp($method); if (self::noMoreElementsInChain($methodNames)) { break; } $mock = self::getNewDemeterMock($container, $method, $exp); } else { $demeterMockKey = $container->getKeyOfDemeterMockFor($method); if ($demeterMockKey) { $mock = self::getExistingDemeterMock($container, $demeterMockKey); } } $nextExp = function ($n) use($mock) { return $mock->shouldReceive($n); }; } return $exp; }
<?php namespace spec\Gaufrette\Adapter; use PHPSpec2\ObjectBehavior; //Hack cause of new version of mongo-ext https://github.com/padraic/mockery/issues/110 \Mockery::getConfiguration()->setInternalClassMethodParamMap("MongoCollection", "aggregate", array('$pipeline', '$op = null', '$some = null')); class GridFS extends ObjectBehavior { /** * @param \MongoGridFS $gridFs */ function let($gridFs) { $this->beConstructedWith($gridFs); } function it_should_be_initializable() { $this->shouldHaveType('Gaufrette\\Adapter\\GridFS'); $this->shouldHaveType('Gaufrette\\Adapter'); } /** * @param \MongoGridFS $gridFs * @param \MongoGridFSFile $file */ function it_should_read_file($gridFs, $file) { $file->getBytes()->willReturn('some content'); $gridFs->findOne('filename', array())->shouldBeCalled()->willReturn($file); $this->read('filename')->shouldReturn('some content'); }
/** * @expectedException \Mockery\Exception */ public function testGlobalConfigMayForbidMockingNonExistentMethodsOnObjects() { \Mockery::getConfiguration()->allowMockingNonExistentMethods(false); $mock = $this->container->mock(new stdClass()); $mock->shouldReceive('foo'); }
public function testGetOneToolByName() { $name = 'name'; m::getConfiguration()->allowMockingNonExistentMethods(true); $this->toolRepo->shouldReceive('findOneByName')->once()->with($name)->andReturn('return'); $this->assertEquals('return', $this->getManager()->getOneToolByName($name)); }
public function testCanCreateNonOverridenInstanceOfPreviouslyOverridenInternalClasses() { \Mockery::getConfiguration()->setInternalClassMethodParamMap('DateTime', 'modify', array('&$string')); // @ used to avoid E_STRICT for incompatible signature @($m = $this->container->mock('DateTime')); $this->assertInstanceOf("Mockery\\MockInterface", $m, "Mocking failed, remove @ error suppresion to debug"); $rc = new ReflectionClass($m); $rm = $rc->getMethod('modify'); $params = $rm->getParameters(); $this->assertTrue($params[0]->isPassedByReference()); \Mockery::getConfiguration()->resetInternalClassMethodParamMaps(); $m = $this->container->mock('DateTime'); $this->assertInstanceOf("Mockery\\MockInterface", $m, "Mocking failed"); $rc = new ReflectionClass($m); $rm = $rc->getMethod('modify'); $params = $rm->getParameters(); $this->assertFalse($params[0]->isPassedByReference()); \Mockery::resetContainer(); \Mockery::getConfiguration()->resetInternalClassMethodParamMaps(); }
private function initMockery() { m::getConfiguration()->allowMockingNonExistentMethods(false); m::getConfiguration()->allowMockingMethodsUnnecessarily(false); }