public function setUp() { $this->unfilteredMessageBroker = $this->getMock('Deicer\\Pubsub\\UnfilteredMessageBrokerInterface'); $this->topicFilteredMessageBroker = $this->getMock('Deicer\\Pubsub\\TopicFilteredMessageBrokerInterface'); $this->messageBuilder = $this->getMock('Deicer\\Pubsub\\MessageBuilderInterface'); $this->composite = $this->getMock('Deicer\\Model\\ModelCompositeInterface'); $this->hydrator = $this->getMock('Deicer\\Model\\RecursiveModelCompositeHydratorInterface'); $this->hydratorException = new TestableHydratorException('Unhandled hydrator exception'); $this->message = $this->getMock('Deicer\\Pubsub\\MessageInterface'); $this->subscriber = $this->getMock('Deicer\\Pubsub\\SubscriberInterface'); $this->message->expects($this->any())->method('getPublisher')->will($this->returnValue($this->fixture)); $this->messageBuilder->expects($this->any())->method('withTopic')->will($this->returnSelf()); $this->messageBuilder->expects($this->any())->method('withContent')->will($this->returnSelf()); $this->messageBuilder->expects($this->any())->method('withPublisher')->will($this->returnSelf()); $this->messageBuilder->expects($this->any())->method('withAttributes')->will($this->returnSelf()); $this->messageBuilder->expects($this->any())->method('build')->will($this->returnValue($this->message)); $this->composite->expects($this->any())->method('count')->will($this->returnValue(0)); // Hydrator returns composite with count equal to array element count $callback = function ($values) { $mockBuilder = new MockGenerator(); $composite = $mockBuilder->getMock('Deicer\\Model\\ModelCompositeInterface'); $composite->expects(TestCase::any())->method('count')->will(TestCase::returnValue(count($values))); return $composite; }; $this->hydrator->expects($this->any())->method('exchangeArray')->with($this->isType('array'))->will($this->returnCallback($callback)); $this->setUpFixture()->setUpFixtureWithExceptionThrowingFetchData()->setUpFixtureWithNonArrayReturningFetchData()->setUpFixtureWithEmptyArrayReturningFetchData()->setUpFixtureWithModelIncompatibleFetchData()->setUpFixtureWithDataProviderDependency()->setUpMockFixture(); }
/** * Get VCS adapter mock * * @return object */ protected static function getVcsAdapterMock() { $generator = new \PHPUnit_Framework_MockObject_Generator(); $vcsAdapter = $generator->getMock('PreCommit\\Vcs\\Git'); $vcsAdapter->expects(self::once())->method('getAffectedFiles')->will(self::returnValue([])); return $vcsAdapter; }
public static function workers() { $mockGenerator = new \PHPUnit_Framework_MockObject_Generator(); $event = 'PHPExtra\\EventManager\\Event\\Event'; $listener = $mockGenerator->getMock('PHPExtra\\EventManager\\Listener\\Listener'); /** @var Listener $listener */ return array(array(array(new Worker(1, $listener, 'dummy1', $event, Priority::NORMAL), new Worker(2, $listener, 'dummy2', $event, Priority::NORMAL), new Worker(3, $listener, 'dummy3', $event, Priority::NORMAL)))); }
/** * Get a plain command-object mock * * @return \Testy\Project */ public static function getPlainMock() { $oMockBuilder = new \PHPUnit_Framework_MockObject_Generator(); $oMock = $oMockBuilder->getMock('\\Testy\\Project'); $oMock->expects(\PHPUnit_Framework_TestCase::any())->method('getName')->will(\PHPUnit_Framework_TestCase::returnValue(\Testy\CLI\Application::NAME)); $oMock->expects(\PHPUnit_Framework_TestCase::any())->method('getProjectHash')->will(\PHPUnit_Framework_TestCase::returnValue(md5(rand()))); return $oMock; }
public function execute(SafeInput $input) : Response { // Use PHPUnit mocks outside of the TestCase... the DSL isn't quite as // pretty here :) $mockgen = new Generator(); $mock = $mockgen->getMock('Psr\\Http\\Message\\ResponseInterface'); $mock->expects(new AtLeastOnce())->method('getStatusCode')->will(new ReturnValue(200)); $mock->expects(new AtLeastOnce())->method('getBody')->will(new ReturnValue(json_encode($input->asArray()))); return $mock; }
/** * Get a plain command-object mock * * @param string $sReturn * * @return \Testy\Util\Command */ public static function getPlainMock($sReturn = '') { $oMockBuilder = new \PHPUnit_Framework_MockObject_Generator(); $oCommandMock = $oMockBuilder->getMock('\\Testy\\Util\\Command'); $oCommandMock->expects(\PHPUnit_Framework_TestCase::any())->method('execute')->will(\PHPUnit_Framework_TestCase::returnSelf()); $oCommandMock->expects(\PHPUnit_Framework_TestCase::any())->method('reset')->will(\PHPUnit_Framework_TestCase::returnSelf()); $oCommandMock->expects(\PHPUnit_Framework_TestCase::any())->method('setCommand')->will(\PHPUnit_Framework_TestCase::returnSelf()); $oCommandMock->expects(\PHPUnit_Framework_TestCase::any())->method('get')->will(\PHPUnit_Framework_TestCase::returnValue($sReturn)); return $oCommandMock; }
/** * Constructor */ public function __construct() { $mockBuilder = new \PHPUnit_Framework_MockObject_Generator(); $this->variableProvider = $mockBuilder->getMock(VariableProviderInterface::class); $this->viewHelperVariableContainer = $mockBuilder->getMock(ViewHelperVariableContainer::class, ['dummy']); $this->viewHelperResolver = $mockBuilder->getMock(ViewHelperResolver::class, ['dummy']); $this->viewHelperInvoker = $mockBuilder->getMock(ViewHelperInvoker::class, ['dummy']); $this->templateParser = $mockBuilder->getMock(TemplateParser::class, ['dummy']); $this->templateCompiler = $mockBuilder->getMock(TemplateCompiler::class, ['dummy']); $this->templatePaths = $mockBuilder->getMock(TemplatePaths::class, ['dummy']); $this->cache = $mockBuilder->getMock(FluidCacheInterface::class); }
/** * @test * @expectedExceptionMessage Pass **/ public function validates_expectations() { $mockBuilder = new PHPUnit_Framework_MockObject_Generator(); $mock = $mockBuilder->getMock('Spy'); $mock->expects($this->once())->method('getValue')->willCallOriginal(); try { $mock->getValue(); $mock->getValue(); $this->fail("Failed to validate expectation on the spy object"); } catch (PHPUnit_Framework_ExpectationFailedException $e) { } }
public static function factory($class, $params = array(), $parent = '') { $mock = \PHPUnit_Framework_MockObject_Generator::getMock($class, array(), array(), '', false); self::bindParameters($mock, $params); $mock->__mocked = $class; return $mock; }
/** * @covers PHPUnit_Framework_MockObject_Generator::getMock */ public function testCanInvokeMethodsOfNonExistentClass() { $className = 'X' . md5(microtime()); $mock = $this->generator->getMock($className, ['someMethod']); $mock->expects($this->once())->method('someMethod'); $this->assertNull($mock->someMethod()); }
/** * @covers Zend\Db\TableGateway\TableGateway::delete */ public function testDelete() { $mockDelete = $this->mockSql->delete(); // assert select::from() is called $mockDelete->expects($this->once())->method('where')->with($this->equalTo('foo')); $this->table->delete('foo'); }
/** * ReflectionClass::getMethods for SoapClient on PHP 5.3 produces PHP Fatal Error * @runInSeparateProcess */ public function testGetMockForSoapClientReflectionMethodsDuplication() { if (version_compare(PHP_VERSION, '5.4.0', '>=')) { $this->markTestSkipped('Only for PHP < 5.4.0'); } $mock = $this->generator->getMock('SoapClient', array(), array(), '', false); $this->assertInstanceOf('SoapClient', $mock); }
/** * @covers PHPUnit_Framework_MockObject_Generator::getMockOverExistingObject */ public function testGetMockOverExistingObject() { $srcObject = new ClassWithProtectedMethod(); $this->assertEquals('real-value', $srcObject->testMethod()); $mock = $this->generator->getMockOverExistingObject($srcObject, []); $mock->expects($this->any())->method('mockableProtectedMethod')->willReturn('test-value'); $this->assertEquals('test-value', $mock->testMethod()); }
function __construct($class, $params = array()) { if (!class_exists($class)) { throw new \RuntimeException("Stubbed class {$class} doesn't exist"); } $this->mockedClass = $class; $this->mock = PHPUnit_Framework_MockObject_Generator::getMock($class, array(), array(), '', false); $this->bindParameters($params); }
/** * Same as "testGetMockForSingletonWithReflectionSuccess", but we expect * warning for PHP < 5.4.0 since PHPUnit will try to execute private __wakeup * on unserialize */ public function testGetMockForSingletonWithUnserializeFail() { if (version_compare(PHP_VERSION, '5.4.0', '>=')) { $this->markTestSkipped('Only for PHP < 5.4.0'); } $this->setExpectedException('PHPUnit_Framework_MockObject_RuntimeException'); // Probably, this should be moved to tests/autoload.php require_once __DIR__ . '/_fixture/SingletonClass.php'; $mock = $this->generator->getMock('SingletonClass', array('doSomething'), array(), '', false); }
/** * Generates a mock object on the singleton Someclass util object. * * @param array $name * @return void */ public static function expects($name, $replace) { // Mock the object $mock = \PHPUnit_Framework_MockObject_Generator::getMock('Someclass', array('hello'), array(), '', false); // Replace protected self reference with mock object $ref = new \ReflectionProperty('Someclass', 'self'); $ref->setAccessible(true); $ref->setValue(null, $mock); // Set expectations and return values $mock->expects(new \PHPUnit_Framework_MockObject_Matcher_InvokedCount(1))->method('hello')->with(\PHPUnit_Framework_Assert::equalTo($name))->will(new \PHPUnit_Framework_MockObject_Stub_Return($replace)); }
public static function getFhirTemplate() { class_exists('DataTemplate'); $template = \PHPUnit_Framework_MockObject_Generator::getMock('DataTemplateComponent', array(), array(), '', false); $template->expects(new \PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount())->method('match')->will(new \PHPUnit_Framework_MockObject_Stub_ReturnCallback(function ($obj, &$warnings) { return get_object_vars($obj); })); $template->expects(new \PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount())->method('generate')->will(new \PHPUnit_Framework_MockObject_Stub_ReturnCallback(function ($values) { return (object) $values; })); return $template; }
protected function generateMock($type, $methods, $mockClassName, $callOriginalClone, $callAutoload, $cloneArguments, $callOriginalMethods) { $namespaceParts = $this->convertNamespace($mockClassName); $parent = parent::generateMock($type, $methods, $namespaceParts['className'], $callOriginalClone, $callAutoload, $cloneArguments, $callOriginalMethods); if (strlen(trim($namespaceParts['namespaceName'])) > 0) { $code = 'namespace ' . $namespaceParts['namespaceName'] . ' {' . PHP_EOL; $code .= preg_replace('/^(class ' . $namespaceParts['className'] . ' extends )(' . $type . ')/', '$1\\\\$2', $parent['code']) . PHP_EOL; $code .= '}'; $parent['code'] = str_replace('PHPUnit_Framework', '\\PHPUnit_Framework', $code); $parent['mockClassName'] = $mockClassName; } return $parent; }
/** * Register mocked package model in di * * @static */ public static function registerDesignMock() { /** @var $packageMock Mage_Core_Model_Design_Package|PHPUnit_Framework_MockObject_MockObject */ $packageMock = PHPUnit_Framework_MockObject_Generator::getMock('Mage_Core_Model_Design_Package', array('getConfigurationDesignTheme'), array(self::_createFilesystem())); $package = Mage::getModel('Mage_Core_Model_Design_Package', array('filesystem' => self::_createFilesystem())); $callBackFixture = function ($area, $params) use($package, $packageMock) { $area = $area ? $area : $packageMock->getArea(); if (isset($params['useId']) && $params['useId'] === false) { return $package->getConfigurationDesignTheme($area, $params); } else { $params['useId'] = false; /** @var $package Mage_Core_Model_Design_Package */ $configPath = $package->getConfigurationDesignTheme($area, $params); return Mage_Core_Utility_Theme::getTheme($configPath, $area)->getId(); } }; $packageMock->expects(new PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount())->method('getConfigurationDesignTheme')->will(new PHPUnit_Framework_MockObject_Stub_ReturnCallback($callBackFixture)); /** @var $objectManager Magento_Test_ObjectManager */ $objectManager = Mage::getObjectManager(); $objectManager->addSharedInstance($packageMock, 'Mage_Core_Model_Design_Package'); }
/** * Returns a mock object based on the given WSDL file. * * @param string $wsdlFile * @param string $originalClassName * @param string $mockClassName * @param array $methods * @param boolean $callOriginalConstructor * @return PHPUnit_Framework_MockObject_MockObject * @since Method available since Release 3.4.0 */ protected function getMockFromWsdl($wsdlFile, $originalClassName = '', $mockClassName = '', array $methods = array(), $callOriginalConstructor = TRUE) { if ($originalClassName === '') { $originalClassName = str_replace('.wsdl', '', basename($wsdlFile)); } eval(PHPUnit_Framework_MockObject_Generator::generateClassFromWsdl($wsdlFile, $originalClassName, $methods)); return $this->getMock($originalClassName, $methods, array('', array()), $mockClassName, $callOriginalConstructor, FALSE, FALSE); }
/** * @covers PHPUnit_Framework_MockObject_Generator::getMockForAbstractClass * @expectedException PHPUnit_Framework_Exception */ public function testGetMockForAbstractClassAnstractClassDoesNotExist() { $mock = PHPUnit_Framework_MockObject_Generator::getMockForAbstractClass('Tux'); }
/** * Returns an object for the specified trait. * * @param string $traitName * @param array $arguments * @param string $traitClassName * @param boolean $callOriginalConstructor * @param boolean $callOriginalClone * @param boolean $callAutoload * @param boolean $cloneArguments * @return object * @since Method available since Release 3.6.0 * @throws PHPUnit_Framework_Exception */ protected function getObjectForTrait($traitName, array $arguments = array(), $traitClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE, $cloneArguments = FALSE) { return PHPUnit_Framework_MockObject_Generator::getObjectForTrait($traitName, $arguments, $traitClassName, $callOriginalConstructor, $callOriginalClone, $callAutoload, $cloneArguments); }
/** * @param string $class_name * @param array $properties */ public static function generate($class_name, array $properties = array()) { $stub = PHPUnit_Framework_MockObject_Generator::getMock($class_name, array(), array(), '', false, false, true, false); self::propertiesSetAndMatch($stub, $properties); return $stub; }
private static function generateMockClass($name, $extends) { $mock_class = \PHPUnit_Framework_MockObject_Generator::generate($extends, null, $name); eval($mock_class['code']); }
/** * @param string $wsdlFile * @param string $originalClassName * @param array $methods * @return array */ public static function generateClassFromWsdl($wsdlFile, $originalClassName, array $methods = array()) { if (self::$soapLoaded === NULL) { self::$soapLoaded = extension_loaded('soap'); } if (self::$soapLoaded) { $client = new SOAPClient($wsdlFile); $_methods = array_unique($client->__getFunctions()); unset($client); $templateDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR; $methodTemplate = new Text_Template($templateDir . 'wsdl_method.tpl'); $methodsBuffer = ''; foreach ($_methods as $method) { $nameStart = strpos($method, ' ') + 1; $nameEnd = strpos($method, '('); $name = substr($method, $nameStart, $nameEnd - $nameStart); if (empty($methods) || in_array($name, $methods)) { $args = explode(',', substr($method, $nameEnd + 1, strpos($method, ')') - $nameEnd - 1)); $numArgs = count($args); for ($i = 0; $i < $numArgs; $i++) { $args[$i] = substr($args[$i], strpos($args[$i], '$')); } $methodTemplate->setVar(array('method_name' => $name, 'arguments' => join(', ', $args))); $methodsBuffer .= $methodTemplate->render(); } } $classTemplate = new Text_Template($templateDir . 'wsdl_class.tpl'); $classTemplate->setVar(array('class_name' => $originalClassName, 'wsdl' => $wsdlFile, 'methods' => $methodsBuffer)); return $classTemplate->render(); } else { throw new PHPUnit_Framework_Exception('The SOAP extension is required to generate a mock object ' . 'from WSDL.'); } }
/** * @return mixed Mocked return value. */ public function generateReturnValue() { switch ($this->returnType) { case '': return; case 'string': return ''; case 'float': return 0.0; case 'int': return 0; case 'bool': return false; case 'array': return []; case 'void': return; case 'callable': case 'Closure': return function () { }; case 'Traversable': case 'Generator': $generator = function () { yield; }; return $generator(); default: $generator = new PHPUnit_Framework_MockObject_Generator(); return $generator->getMock($this->returnType, [], [], '', false); } }
/** * Replace the Laravel event dispatcher with a mock. */ private function mockEventDispatcher() { $mockGenerator = new \PHPUnit_Framework_MockObject_Generator(); $mock = $mockGenerator->getMock('Illuminate\\Contracts\\Events\\Dispatcher'); $this->app->instance('events', $mock); }
/** * Specifies the subset of methods to not mock. Default is to mock all of them. * * @param array $methods * * @return PHPUnit_Framework_MockObject_MockBuilder */ public function setMethodsExcept(array $methods = []) { $this->methodsExcept = $methods; $this->setMethods(array_diff($this->generator->getClassMethods($this->type), $this->methodsExcept)); return $this; }
/** * @param $className * @return PHPUnit_Framework_MockObject_MockObject */ function getMockForAbstractClass($className) { return PHPUnit_Framework_MockObject_Generator::getMockForAbstractClass($className); }
/** * @covers PHPUnit_Framework_MockObject_Generator::getMock * @expectedException PHPUnit_Framework_MockObject_RuntimeException */ public function testExceptionIsRaisedForMutuallyExclusiveOptions() { $this->generator->getMock(StdClass::class, [], [], '', false, true, true, true, true); }