public function getMock() { $mock = $this->testCase->getMock('stdClass', $this->functions, array(), 'PHPUnit_Extension_FunctionMocker_' . uniqid()); foreach ($this->functions as $function) { $fqFunction = $this->namespace . '\\' . $function; if (in_array($fqFunction, static::$mockedFunctions, true)) { continue; } if (!extension_loaded('runkit') || !ini_get('runkit.internal_override')) { PHPUnit_Extension_FunctionMocker_CodeGenerator::defineFunction($function, $this->namespace); } elseif (!function_exists('__phpunit_function_mocker_' . $function)) { runkit_function_rename($function, '__phpunit_function_mocker_' . $function); error_log($function); runkit_method_redefine($function, function () use($function) { if (!isset($GLOBALS['__PHPUNIT_EXTENSION_FUNCTIONMOCKER'][$this->namespace])) { return call_user_func_array('__phpunit_function_mocker_' . $function, func_get_args()); } return call_user_func_array(array($GLOBALS['__PHPUNIT_EXTENSION_FUNCTIONMOCKER'][$this->namespace], $function), func_get_args()); }); var_dump(strlen("foo")); } static::$mockedFunctions[] = $fqFunction; } if (!isset($GLOBALS['__PHPUNIT_EXTENSION_FUNCTIONMOCKER'])) { $GLOBALS['__PHPUNIT_EXTENSION_FUNCTIONMOCKER'] = array(); } $GLOBALS['__PHPUNIT_EXTENSION_FUNCTIONMOCKER'][$this->namespace] = $mock; return $mock; }
/** * @param \PHPUnit_Framework_TestCase $test * @param \Closure $qbCallback * @param array $fields * * @return \Doctrine\ORM\EntityManagerInterface */ public static function create(\PHPUnit_Framework_TestCase $test, \Closure $qbCallback, $fields) { $query = $test->getMockForAbstractClass('Doctrine\\ORM\\AbstractQuery', [], '', false, true, true, ['execute']); $query->expects($test->any())->method('execute')->will($test->returnValue(true)); if (Version::compare('2.5.0') < 1) { $entityManager = $test->getMock('Doctrine\\ORM\\EntityManagerInterface'); $qb = $test->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->setConstructorArgs([$entityManager])->getMock(); } else { $qb = $test->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->disableOriginalConstructor()->getMock(); } $qb->expects($test->any())->method('select')->will($test->returnValue($qb)); $qb->expects($test->any())->method('getQuery')->will($test->returnValue($query)); $qb->expects($test->any())->method('where')->will($test->returnValue($qb)); $qb->expects($test->any())->method('orderBy')->will($test->returnValue($qb)); $qb->expects($test->any())->method('andWhere')->will($test->returnValue($qb)); $qb->expects($test->any())->method('leftJoin')->will($test->returnValue($qb)); $qbCallback($qb); $repository = $test->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock(); $repository->expects($test->any())->method('createQueryBuilder')->will($test->returnValue($qb)); $metadata = $test->getMock('Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata'); $metadata->expects($test->any())->method('getFieldNames')->will($test->returnValue($fields)); $metadata->expects($test->any())->method('getName')->will($test->returnValue('className')); $em = $test->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $em->expects($test->any())->method('getRepository')->will($test->returnValue($repository)); $em->expects($test->any())->method('getClassMetadata')->will($test->returnValue($metadata)); return $em; }
/** * Retrieve new layout model instance with layout updates from a fixture file * * @param string|array $layoutUpdatesFile * @param array $args * @return \Magento\Framework\View\Layout|\PHPUnit_Framework_MockObject_MockObject */ public function getLayoutFromFixture($layoutUpdatesFile, array $args = []) { $layout = $this->_testCase->getMock('Magento\\Framework\\View\\Layout', ['getUpdate'], $args); $layoutUpdate = $this->getLayoutUpdateFromFixture($layoutUpdatesFile); $layoutUpdate->asSimplexml(); $layout->expects(\PHPUnit_Framework_TestCase::any())->method('getUpdate')->will(\PHPUnit_Framework_TestCase::returnValue($layoutUpdate)); return $layout; }
public function getAuthorization($result, $resolved = true) { $authorizationMockup = $this->object->getMock("ResolveAuth\\Authorization\\Resolvable\\ResolvableAuthorization", ['value', 'state', 'resolve', 'afterResolve', 'resolved'], [], '', false); $authorizationMockup->method('value')->willReturn($result); $authorizationMockup->method('resolved')->willReturn($resolved); $authorizationMockup->method('state')->willReturn($result); return $authorizationMockup; }
/** * Retrieve new layout model instance with layout updates from a fixture file * * @param string $layoutUpdatesFile * @param array $args * @return Mage_Core_Model_Layout|PHPUnit_Framework_MockObject_MockObject */ public function getLayoutFromFixture($layoutUpdatesFile, array $args = array()) { $layout = $this->_testCase->getMock('Mage_Core_Model_Layout', array('getUpdate'), $args); $layoutUpdate = $this->getLayoutUpdateFromFixture($layoutUpdatesFile); $layoutUpdate->asSimplexml(); $layout->expects(PHPUnit_Framework_TestCase::any())->method('getUpdate')->will(PHPUnit_Framework_TestCase::returnValue($layoutUpdate)); return $layout; }
/** * Return mocks with expected invokes * * First element is quoteIdMaskFactoryMock, second one is quoteIdMaskMock * * @param $maskedCartId * @param $cartId * @return array */ public function mockQuoteIdMask($maskedCartId, $cartId) { $quoteIdMaskMock = $this->testCase->getMock('Magento\\Quote\\Model\\QuoteIdMask', ['load', 'getQuoteId', 'getMaskedId'], [], '', false); $quoteIdMaskFactoryMock = $this->testCase->getMockBuilder('Magento\\Quote\\Model\\QuoteIdMaskFactory')->setMethods(['create'])->disableOriginalConstructor()->getMock(); $quoteIdMaskFactoryMock->expects($this->testCase->once())->method('create')->willReturn($quoteIdMaskMock); $quoteIdMaskMock->expects($this->testCase->once())->method('load')->with($maskedCartId)->willReturnSelf(); $quoteIdMaskMock->expects($this->testCase->once())->method('getQuoteId')->willReturn($cartId); return [$quoteIdMaskFactoryMock, $quoteIdMaskMock]; }
/** * Creates and instance of a mock Joomla\Cache\Item object. * * @return object * * @since 1.0 */ public function createMockItem() { // Collect all the relevant methods in JDatabase. $methods = array('getKey', 'getValue', 'isHit', 'setValue'); // Create the mock. $mockObject = $this->test->getMock('Joomla\\Cache\\Item', $methods, array(), '', false); TestHelper::assignMockCallbacks($mockObject, $this->test, array('getValue' => array(is_callable(array($this->test, 'mockCacheItemGetValue')) ? $this->test : $this, 'mockCacheItemGetValue'), 'isHit' => array(is_callable(array($this->test, 'mockCacheItemIsHit')) ? $this->test : $this, 'mockCacheItemIsHit'))); return $mockObject; }
/** * @param Identifies $id * @return \PHPUnit_Framework_MockObject_MockObject */ public function mockAggregate(Identifies $id) { $class = 'SimpleES\\EventSourcing\\Aggregate\\TracksEvents'; $aggregate = $this->testCase->getMock($class); $aggregate->expects($this->testCase->any())->method('aggregateId')->will($this->testCase->returnValue($id)); return $aggregate; }
/** * Creates an instance of a mock JInput object. * * @param array $options An associative array of options to configure the mock. * * methods => an array of additional methods to mock * * @return PHPUnit_Framework_MockObject_MockObject * * @since 3.4 */ public function createInput(array $options = null) { // Collect all the relevant methods in JInput. $methods = array('count', 'def', 'get', 'getArray', 'getInt', 'getMethod', 'set', 'serialize', 'unserialize'); // Add custom methods if required for derived application classes. if (isset($options['methods']) && is_array($options['methods'])) { $methods = array_merge($methods, $options['methods']); } // Create the mock. $mockObject = self::$test->getMock('JInput', $methods, array(), '', false); self::$test->assignMockCallbacks($mockObject, array('get' => array(is_callable(array(self::$test, 'mockInputGet')) ? self::$test : $this, 'mockInputGet'), 'getArray' => array(is_callable(array(self::$test, 'mockInputGetArray')) ? self::$test : $this, 'mockInputGetArray'), 'getInt' => array(is_callable(array(self::$test, 'mockInputGetInt')) ? self::$test : $this, 'mockInputGetInt'), 'set' => array(is_callable(array(self::$test, 'mockInputSet')) ? self::$test : $this, 'mockInputSet'))); $mockObject->get = $mockObject; $mockObject->post = $mockObject; $mockObject->request = $mockObject; return $mockObject; }
/** * * @param string $username * @return \Nethgui\Authorization\UserInterface */ public static function getAuthenticationSubject(\PHPUnit_Framework_TestCase $testcase, $username = FALSE, $groups = array()) { $subject = $testcase->getMock('Nethgui\\Authorization\\User', array('authenticate', 'isAuthenticated', 'getCredential', 'hasCredential', 'getLanguageCode', 'asAuthorizationString', 'getAuthorizationAttribute')); $subject->expects($testcase->any())->method('isAuthenticated')->will($testcase->returnValue(is_string($username))); $subject->expects($testcase->any())->method('getCredential')->with('username')->will($testcase->returnValue(is_string($username) ? $username : NULL)); $subject->expects($testcase->any())->method('hasCredential')->with('username')->will($testcase->returnValue(is_string($username))); $getAttribute = function ($attName) use($username, $groups) { if ($attName === 'username') { return is_string($username) ? $username : NULL; } elseif ($attName === 'authenticated') { return is_string($username) ? TRUE : FALSE; } elseif ($attName == 'groups') { return $groups; } return NULL; }; $subject->expects($testcase->any())->method('getAuthorizationAttribute')->withAnyParameters()->will($testcase->returnCallback($getAttribute)); $subject->expects($testcase->any())->method('asAuthorizationString')->will($testcase->returnValue(is_string($username) ? $username : '******')); $subject->hasCredential('username'); $subject->getCredential('username'); $subject->isAuthenticated(); $subject->getAuthorizationAttribute('username'); $subject->asAuthorizationString(); return $subject; }
/** * Creates and instance of the mock AbstractModel object. * * @param \PHPUnit_Framework_TestCase $test A test object. * * @return object * * @since 1.0 */ public static function create(\PHPUnit_Framework_TestCase $test) { // Collect all the relevant methods in AbstractModel. $methods = array('getState', 'loadState', 'setState'); // Create the mock. $mockObject = $test->getMock('Joomla\\Model\\ModelInterface', $methods, array(), '', false); return $mockObject; }
/** * Creates an instance of the mock JAccessRules object. * * @param PHPUnit_Framework_TestCase $test A test object. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 11.3 */ public static function create($test) { // Mock all the public methods. $methods = array('allow'); // Create the mock. $mockObject = $test->getMock('JAccessRules', $methods, array(), '', false); $test->assignMockCallbacks($mockObject, array('allow' => array(get_called_class(), 'mockAllow'))); return $mockObject; }
/** * Get collection mock * * @param string $className * @param array $data * @return \PHPUnit_Framework_MockObject_MockObject * @throws \InvalidArgumentException */ public function getCollectionMock($className, array $data) { if (!is_subclass_of($className, '\\Magento\\Framework\\Data\\Collection')) { throw new \InvalidArgumentException($className . ' does not instance of \\Magento\\Framework\\Data\\Collection'); } $mock = $this->_testObject->getMock($className, [], [], '', false, false); $iterator = new \ArrayIterator($data); $mock->expects($this->_testObject->any())->method('getIterator')->will($this->_testObject->returnValue($iterator)); return $mock; }
/** * Creates and instance of the mock JLanguage object. * * @param PHPUnit_Framework_TestCase $test A test object. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 11.3 */ public static function create($test) { // Collect all the relevant methods in JDatabase. $methods = array('parse', 'render', 'test'); // Create the mock. $mockObject = $test->getMock('JDocument', $methods, array(), '', false); // Mock selected methods. $test->assignMockReturns($mockObject, array('parse' => $mockObject, 'test' => 'ok')); return $mockObject; }
/** * @param \PHPUnit_Framework_TestCase $testCase * * @param array $classes */ public function __construct(\PHPUnit_Framework_TestCase $testCase, array $classes = []) { $configProvider = $testCase->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProvider')->disableOriginalConstructor()->getMock(); $entityClassResolver = $testCase->getMockBuilder('Oro\\Bundle\\EntityBundle\\ORM\\EntityClassResolver')->disableOriginalConstructor()->getMock(); $entityClassResolver->expects($testCase->any())->method('getEntityClass')->willReturnArgument(0); $container = $testCase->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface'); $container->expects($testCase->any())->method('get')->will($testCase->returnValueMap([['oro_entity_config.provider.ownership', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $configProvider], ['oro_entity.orm.entity_class_resolver', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $entityClassResolver]])); parent::__construct(array_merge(['organization' => 'Oro\\Bundle\\SecurityBundle\\Tests\\Unit\\Acl\\Domain\\Fixtures\\Entity\\Organization', 'business_unit' => 'Oro\\Bundle\\SecurityBundle\\Tests\\Unit\\Acl\\Domain\\Fixtures\\Entity\\BusinessUnit', 'user' => 'Oro\\Bundle\\SecurityBundle\\Tests\\Unit\\Acl\\Domain\\Fixtures\\Entity\\User'], $classes)); $this->setContainer($container); }
/** * Creates and instance of the mock JDatabaseDriver object. * * @param PHPUnit_Framework_TestCase $test A test object. * @param string $driver Optional driver to create a sub-class of JDatabaseDriver. * @param array $extraMethods An array of additional methods to add to the mock. * @param string $nullDate A null date string for the driver. * @param string $dateFormat A date format for the driver. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 11.3 */ public static function create($test, $driver = '', array $extraMethods = array(), $nullDate = '0000-00-00 00:00:00', $dateFormat = 'Y-m-d H:i:s') { // Collect all the relevant methods in JDatabaseDriver. $methods = array_merge($extraMethods, array('connect', 'connected', 'disconnect', 'dropTable', 'escape', 'execute', 'fetchArray', 'fetchAssoc', 'fetchObject', 'freeResult', 'getAffectedRows', 'getCollation', 'getConnectors', 'getDateFormat', 'getErrorMsg', 'getErrorNum', 'getInstance', 'getLog', 'getNullDate', 'getNumRows', 'getPrefix', 'getQuery', 'getTableColumns', 'getTableCreate', 'getTableKeys', 'getTableList', 'getUtfSupport', 'getVersion', 'insertId', 'insertObject', 'loadAssoc', 'loadAssocList', 'loadColumn', 'loadObject', 'loadObjectList', 'loadResult', 'loadRow', 'loadRowList', 'lockTable', 'query', 'quote', 'quoteName', 'renameTable', 'replacePrefix', 'select', 'setQuery', 'setUTF', 'splitSql', 'test', 'isSupported', 'transactionCommit', 'transactionRollback', 'transactionStart', 'unlockTables', 'updateObject')); // Create the mock. $mockObject = $test->getMock('JDatabaseDriver' . $driver, $methods, array(), '', false); // Mock selected methods. $test->assignMockReturns($mockObject, array('getNullDate' => $nullDate, 'getDateFormat' => $dateFormat)); $test->assignMockCallbacks($mockObject, array('escape' => array(is_callable(array($test, 'mockEscape')) ? $test : __CLASS__, 'mockEscape'), 'getQuery' => array(is_callable(array($test, 'mockGetQuery')) ? $test : __CLASS__, 'mockGetQuery'), 'quote' => array(is_callable(array($test, 'mockQuote')) ? $test : __CLASS__, 'mockQuote'), 'quoteName' => array(is_callable(array($test, 'mockQuoteName')) ? $test : __CLASS__, 'mockQuoteName'), 'setQuery' => array(is_callable(array($test, 'mockSetQuery')) ? $test : __CLASS__, 'mockSetQuery'))); return $mockObject; }
/** * Creates and instance of the mock JLanguage object. * * @param PHPUnit_Framework_TestCase $test A test object. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 11.3 */ public static function create($test) { // Collect all the relevant methods in JDatabase. $methods = array('_', 'getInstance', 'getTag', 'test'); // Create the mock. $mockObject = $test->getMock('JLanguage', $methods, array(), '', false); // Mock selected methods. $test->assignMockReturns($mockObject, array('getInstance' => $mockObject, 'getTag' => 'en-GB', 'test' => 'ok')); $test->assignMockCallbacks($mockObject, array('_' => array(get_called_class(), 'mock_'))); return $mockObject; }
/** * @return \PHPUnit_Framework_MockObject_MockObject */ public function createMock() { $methods = $this->mockMethods; $allMethodsNames = array_unique(array_merge(array_keys($methods), array_keys($this->originClassMethods))); $this->mock = $this->testCase->getMock($this->className, $allMethodsNames, array(), '', false, false, false); foreach ($methods as $methodName => $method) { $this->buildMethod($methodName); } $this->createUndeclaredMethods(); return $this->mock; }
/** * Creates an instance of the mock Input object. * * @param \PHPUnit_Framework_TestCase $test A test object. * @param array|\ArrayAccess $extraMethods An array of additional methods to add to the mock. * * @return \PHPUnit_Framework_MockObject_MockObject * * @since 1.0 */ public function create($test, $extraMethods = array()) { // Collect all the relevant methods in Input. $methods = array_merge($extraMethods, ['count', 'def', 'exists', 'get', 'getArray', 'getInt', 'getMethod', 'loadAllInputs', 'set', 'serialize', 'unserialize']); // Create the mock. $mockObject = $test->getMock('\\Joomla\\Input\\Input', $methods, [], '', false); $this->assignMockCallbacks($test, $mockObject, ['get' => [is_callable([$test, 'mockInputGet']) ? $test : get_called_class(), 'mockInputGet'], 'getArray' => [is_callable([$test, 'mockInputGetArray']) ? $test : get_called_class(), 'mockInputGetArray'], 'getInt' => [is_callable([$test, 'mockInputGetInt']) ? $test : get_called_class(), 'mockInputGetInt'], 'set' => [is_callable([$test, 'mockInputSet']) ? $test : get_called_class(), 'mockInputSet']]); $mockObject->get = $mockObject; $mockObject->post = $mockObject; $mockObject->request = $mockObject; return $mockObject; }
/** * Dispatch a page, using the supplied page name (e.g. "Index" or "Edit") * and request data. If you supply any POST data, the request method will * be set to POST as well. * * @param string $name * @param array $post * @param array $query * @return \Dewdrop\Admin\Response\MockResponse */ public function dispatchPage($name, array $post = array(), array $query = array()) { $request = $this->createRequest($post, $query); $component = $this->getComponent($request); $mockedMethods = array('render'); if ($this->mockResponseHelper) { $mockedMethods[] = 'executeHelper'; } $response = $this->testCase->getMock('\\Dewdrop\\Admin\\Response', $mockedMethods, array()); $component->route($name, $response); return $response; }
/** * Creates a mock object using a fluent interface. * * @return PHPUnit_Framework_MockObject_MockObject */ public function getMock() { return $this->testCase->getMock( $this->className, $this->methods, $this->constructorArgs, $this->mockClassName, $this->originalConstructor, $this->originalClone, $this->autoload ); }
/** * Creates an instance of the mock JMenu object. * * @param object $test A test object. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 3.4 */ public static function create(PHPUnit_Framework_TestCase $test) { $methods = array('getItem', 'setActive', 'getActive', 'getItems'); // Create the mock. $mockObject = $test->getMock('JMenu', $methods, array(), '', false); if (count(self::$data) == 0) { self::createMenuSampleData(); } $mockObject->expects($test->any())->method('getItem')->will($test->returnValueMap(self::$data)); $mockObject->expects($test->any())->method('getActive')->will($test->returnValue(self::$data[self::$active])); $mockObject->expects($test->any())->method('getItems')->will($test->returnValue(self::$data)); return $mockObject; }
public function init() { $wikiaAppArgs = array(); $globalRegistryMock = null; $functionWrapperMock = null; $globalRegistryMock = $this->testCase->getMock('WikiaGlobalRegistry', array('get', 'set')); $globalRegistryMock->expects($this->testCase->any())->method('get')->will($this->testCase->returnCallback(array($this, 'getGlobalCallback'))); if (in_array('runFunction', $this->methods)) { $functionWrapperMock = $this->testCase->getMock('WikiaFunctionWrapper', array_keys($this->mockedFunctions)); foreach ($this->mockedFunctions as $functionName => $functionData) { $functionWrapperMock->expects($this->testCase->exactly($functionData['calls']))->method($functionName)->will($this->testCase->returnValue($functionData['value'])); } } $wikiaAppArgs[] = $globalRegistryMock; $wikiaAppArgs[] = null; // WikiaLocalRegistry $wikiaAppArgs[] = null; // WikiaHookDispatcher $wikiaAppArgs[] = $functionWrapperMock; $this->mock = $this->testCase->getMock('WikiaApp', array('ajax'), $wikiaAppArgs, ''); F::setInstance('App', $this->mock); }
/** * Construct * * @param string $functionName * @param PHPUnit_Framework_TestCase $testCase */ public function __construct($functionName, PHPUnit_Framework_TestCase $testCase) { $this->functionName = $functionName; $this->functionAlias = uniqid("{$functionName}_"); if (!function_exists($functionName)) { throw new InvalidArgumentException("Invalid function name '{$functionName}'"); } if (array_key_exists($functionName, self::$mockObjects)) { throw new RuntimeException("Can not create second function mock for '{$functionName}'"); } self::$mockObjects[$functionName] = $testCase->getMock($this->functionAlias, array('call')); $this->enable(); }
/** * Construct * * @param string $function * @param PHPUnit_Framework_TestCase $testcase */ public function __construct($function, PHPUnit_Framework_TestCase $testcase) { if (!function_exists($function)) { throw new InvalidArgumentException("Invalid function name '{$function}'"); } if (array_key_exists($function, self::$mock_objects)) { throw new RuntimeException("Can not create second function mock for '{$function}'"); } $this->_function_name = $function; $this->_function_alias = uniqid("function_"); self::$mock_objects[$this->_function_name] = $testcase->getMock($this->_function_alias, array('call')); $this->mock(); }
/** * Construct * * @param string $_class_name * @param PHPUnit_Framework_TestCase $testcase */ public function __construct($class, $methods, PHPUnit_Framework_TestCase $testcase) { if (!class_exists($class)) { throw new InvalidArgumentException("Invalid class name '{$class}'"); } if (array_key_exists($class, self::$mock_objects)) { throw new RuntimeException("Can not create second class mock for '{$class}'"); } $this->_class_name = $class; $this->_class_alias = uniqid("class_"); $this->_methods = is_string($methods) ? [$methods] : $methods; self::$mock_objects[$this->_class_name] = $testcase->getMock($this->_class_alias, $this->_methods); $this->mock(); }
/** * Creates an instance of the mock JSession object. * * @param PHPUnit_Framework_TestCase $test A test object. * @param array $options An array of optional configuration values. * getId : the value to be returned by the mock getId method * get.user.id : the value to assign to the user object id returned by get('user') * get.user.name : the value to assign to the user object name returned by get('user') * get.user.username : the value to assign to the user object username returned by get('user') * * @return PHPUnit_Framework_MockObject_MockObject * * @since 11.3 */ public static function create($test, $options = array()) { if (is_array($options)) { self::$options = $options; } // Mock all the public methods. $methods = array('clear', 'close', 'destroy', 'fork', 'get', 'getExpire', 'getFormToken', 'getId', 'getInstance', 'getName', 'getState', 'getStores', 'getToken', 'has', 'hasToken', 'getPrefix', 'isNew', 'restart', 'set'); // Create the mock. $mockObject = $test->getMock('JSession', $methods, array(), '', false); // Mock selected methods. $test->assignMockReturns($mockObject, array('getId' => self::getOption('getId'))); $test->assignMockCallbacks($mockObject, array('get' => array(get_called_class(), 'mockGet'))); return $mockObject; }
/** * Call API method via API handler. * * @param \PHPUnit_Framework_TestCase $testCase Active test case * @param string $path * @param array $params Order of items matters as they are passed to call_user_func_array * @return mixed */ public static function call(\PHPUnit_Framework_TestCase $testCase, $path, $params = array()) { $soapAdapterMock = $testCase->getMock('Magento\\Api\\Model\\Server\\Adapter\\Soap', array('fault')); $soapAdapterMock->expects($testCase->any())->method('fault')->will($testCase->returnCallback(array(__CLASS__, 'soapAdapterFaultCallback'))); $serverMock = $testCase->getMock('Magento\\Api\\Model\\Server', array('getAdapter')); $serverMock->expects($testCase->any())->method('getAdapter')->will($testCase->returnValue($soapAdapterMock)); $apiSessionMock = $testCase->getMock('Magento\\Api\\Model\\Session', array('isAllowed', 'isLoggedIn'), array(), '', false); $apiSessionMock->expects($testCase->any())->method('isAllowed')->will($testCase->returnValue(true)); $apiSessionMock->expects($testCase->any())->method('isLoggedIn')->will($testCase->returnValue(true)); $handlerMock = $testCase->getMock('Magento\\Api\\Model\\Server\\Handler\\Soap', array('_getServer', '_getSession'), array(), '', false); self::$_previousHandler = set_error_handler(array($handlerMock, 'handlePhpError')); $handlerMock->expects($testCase->any())->method('_getServer')->will($testCase->returnValue($serverMock)); $handlerMock->expects($testCase->any())->method('_getSession')->will($testCase->returnValue($apiSessionMock)); array_unshift($params, 'sessionId'); /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $objectManager->get('Magento\\Framework\\Registry')->unregister('isSecureArea'); $objectManager->get('Magento\\Framework\\Registry')->register('isSecureArea', true); $result = call_user_func_array(array($handlerMock, $path), $params); $objectManager->get('Magento\\Framework\\Registry')->unregister('isSecureArea'); $objectManager->get('Magento\\Framework\\Registry')->register('isSecureArea', false); self::restoreErrorHandler(); return $result; }
/** * Creates and instance of the mock JEventDispatcher object. * * @param PHPUnit_Framework_TestCase $test A test object. * @param boolean $defaults True to create the default mock handlers and triggers. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 11.3 */ public static function create($test, $defaults = true) { // Clear the static tracker properties. self::$handlers = array(); self::$triggered = array(); // Collect all the relevant methods in JEventDispatcher. $methods = array('register', 'trigger', 'test'); // Create the mock. $mockObject = $test->getMock('JEventDispatcher', $methods, array(), '', false); // Mock selected methods. $test->assignMockReturns($mockObject, array('test' => 'ok')); if ($defaults) { $test->assignMockCallbacks($mockObject, array('register' => array(get_called_class(), 'mockRegister'), 'trigger' => array(get_called_class(), 'mockTrigger'))); } return $mockObject; }
/** * Creates an instance of the mock DatabaseDriver object. * * @param \PHPUnit_Framework_TestCase $test A test object. * @param string $driver Optional driver to create a sub-class of DatabaseDriver. * @param array|\ArrayAccess $extraMethods An array of additional methods to add to the mock. * @param string $nullDate A null date string for the driver. * @param string $dateFormat A date format for the driver. * * @return \PHPUnit_Framework_MockObject_MockObject * * @since 1.0 */ public function create($test, $driver = '', $extraMethods = array(), $nullDate = '0000-00-00 00:00:00', $dateFormat = 'Y-m-d H:i:s') { // Collect all the relevant methods in DatabaseDriver and merge any additional parameters $methods = array_merge($extraMethods, ['getConnectors', 'getInstance', 'splitSql', 'connect', 'connected', 'disconnect', 'dropTable', 'escape', 'fetchArray', 'fetchAssoc', 'fetchObject', 'freeResult', 'getAffectedRows', 'getCollation', 'getConnection', 'getCount', 'getDatabase', 'getDateFormat', 'getMinimum', 'getNullDate', 'getNumRows', 'getPrefix', 'getExporter', 'getImporter', 'getQuery', 'getIterator', 'getTableColumns', 'getTableCreate', 'getTableKeys', 'getTableList', 'hasUTFSupport', 'getVersion', 'insertid', 'insertObject', 'isMinimumVersion', 'loadAssoc', 'loadAssocList', 'loadColumn', 'loadObject', 'loadObjectList', 'loadResult', 'loadRow', 'loadRowList', 'log', 'lockTable', 'quote', 'quoteName', 'quoteNameStr', 'replacePrefix', 'renameTable', 'select', 'setDebug', 'setQuery', 'setLogger', 'setUTF', 'transactionCommit', 'transactionRollback', 'transactionStart', 'truncateTable', 'updateObject', 'execute', 'unlockTables']); if (empty($driver)) { $class = '\\Joomla\\Database\\DatabaseDriver'; } else { $class = '\\Joomla\\Database\\' . ucfirst(strtolower($driver)) . '\\' . ucfirst(strtolower($driver)) . 'Driver'; } // Create the mock. $mockObject = $test->getMock($class, $methods, [['driver' => $driver]], '', false); // Mock selected methods. $this->assignMockReturns($test, $mockObject, ['getNullDate' => $nullDate, 'getDateFormat' => $dateFormat]); $this->assignMockCallbacks($test, $mockObject, ['escape' => [is_callable([$test, 'mockEscape']) ? $test : get_called_class(), 'mockEscape'], 'getQuery' => [is_callable([$test, 'mockGetQuery']) ? $test : get_called_class(), 'mockGetQuery'], 'quote' => [is_callable([$test, 'mockQuote']) ? $test : get_called_class(), 'mockQuote'], 'quoteName' => [is_callable([$test, 'mockQuoteName']) ? $test : get_called_class(), 'mockQuoteName'], 'setQuery' => [is_callable([$test, 'mockSetQuery']) ? $test : get_called_class(), 'mockSetQuery']]); static::$dbo = $mockObject; return $mockObject; }