/** * @param $isDue * @return \Trovit\CronManagerBundle\Model\CronExpressionWrapper|\PHPUnit_Framework_MockObject_MockObject */ public function getCronDispatcherTestMock($isDue) { $mock = $this->getBasicMock(); $cronExpressionMocks = new CronExpressionMocks($this->_testCase); $mock->expects($this->_testCase->any())->method('createCronExpression')->willReturn($cronExpressionMocks->getCronDispatcherTestMock($isDue)); return $mock; }
/** * * @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; }
/** * Create a new mock of the curlbuilder and return * the given filename as content * * @access public * @param PHPUnit_Framework_TestCase $instance * @return mock */ public static function create($instance) { $reflection = new \ReflectionMethod($instance, $instance->getName()); $doc_block = $reflection->getDocComment(); $responsefile = self::parseDocBlock($doc_block, '@responsefile'); $responsecode = self::parseDocBlock($doc_block, '@responsecode'); $defaultheaders = array("X-Ratelimit-Limit" => "1000", "X-Ratelimit-Remaining" => "998", "X-Varnish" => "4059929980"); $skipmock = self::parseDocBlock($doc_block, '@skipmock'); if (empty($responsecode)) { $responsecode = [201]; } if (empty($responsefile)) { $responsefile = [$instance->getName()]; } // Setup Curlbuilder mock $curlbuilder = $instance->getMockBuilder("\\DirkGroenen\\Pinterest\\Utils\\CurlBuilder")->getMock(); $curlbuilder->expects($instance->any())->method('create')->will($instance->returnSelf()); // Build response file path $responseFilePath = __DIR__ . '/../responses/' . (new \ReflectionClass($instance))->getShortName() . '/' . $responsefile[0] . ".json"; if (file_exists($responseFilePath)) { $curlbuilder->expects($instance->once())->method('execute')->will($instance->returnValue(file_get_contents($responseFilePath))); } $curlbuilder->expects($instance->any())->method('getInfo')->will($instance->returnValue($responsecode[0])); return $curlbuilder; }
/** * @param PHPUnit_Framework_MockObject_MockObject $stub */ protected function loadMethodStubs($stub) { foreach ($this->fields as $field => $will) { $will = $this->buildStub($will); $methodConstraint = new TestDataBuilder_SimpleEqualsConstraint($field); $stub->expects($this->testCase->any())->method($methodConstraint)->will($will); } }
/** * @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 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; }
/** * @param string $path * @param TestCase $testCase * @return RequestInterface */ public static function fromFixture($path, TestCase $testCase) { $content = file_get_contents($path); $lines = explode("\n", $content); $request = $testCase->getMockBuilder(RequestInterface::class)->getMock(); $line = array_shift($lines); list($method, $uri, $ver) = explode(' ', $line); $request->expects(TestCase::any())->method('getMethod')->willReturn($method); $headerValues = []; $headers = []; while (($line = array_shift($lines)) != "") { list($key, $value) = explode(': ', $line); $headers[$key] = $value; $headerValues[$key] = explode(', ', $value); } $request->expects(TestCase::any())->method('getHeaders')->willReturn($headerValues); $request->expects(TestCase::any())->method('getHeaderLine')->willReturnCallback(function ($key) use($headers) { return isset($headers[$key]) ? $headers[$key] : null; }); $request->expects(TestCase::any())->method('hasHeader')->willReturnCallback(function ($key) use($headers) { return isset($headers[$key]); }); $request->expects(TestCase::any())->method('getBody')->willReturn($body = join("\n", $lines)); return $request; }
/** * @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; }
/** * 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; }
/** * 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; }
/** * Creates and instance of the mock object. * * @param PHPUnit_Framework_TestCase $test A test object. * * @return PHPUnit_Framework_MockObject_MockObject */ public static function create($test) { // Collect all the relevant methods in JDatabase. $methods = array('getIssueId', 'setIssueId', 'getIssue', 'getIssueProject', 'getIssues'); // Create the mock. $mockObject = $test->getMock('MonitorModelIssue', $methods, array(), '', false); self::createSampleData(); $setterCallback = function ($id) { self::$issueId = $id; }; $mockObject->expects($test->any())->method('setIssueId')->will($test->returnCallback($setterCallback)); $mockObject->expects($test->any())->method('getIssueId')->will($test->returnValue(self::$issueId)); $mockObject->expects($test->any())->method('getIssue')->will($test->returnValue(self::$data[self::$issueId])); $mockObject->expects($test->any())->method('getIssueProject')->will($test->returnValue(1)); $mockObject->expects($test->any())->method('getIssues')->will($test->returnValue(self::$data)); return $mockObject; }
/** * Creates an instance of the mock JMenu object. * * @param PHPUnit_Framework_TestCase $test A test object. * * @return PHPUnit_Framework_MockObject_MockObject * * @since 3.4 */ public static function create(PHPUnit_Framework_TestCase $test, $setDefault = true, $setActive = false) { // Collect all the relevant methods in JMenu (work in progress). $methods = array('getItem', 'setDefault', 'getDefault', 'setActive', 'getActive', 'getItems', 'getParams', 'getMenu', 'authorise', 'load'); // Create the mock. $mockObject = $test->getMock('JMenu', $methods, array(), '', false); self::createMenuSampleData(); $mockObject->expects($test->any())->method('getItem')->will($test->returnValueMap(self::prepareGetItemData())); $mockObject->expects($test->any())->method('getMenu')->will($test->returnValue(self::$data)); if ($setDefault) { $mockObject->expects($test->any())->method('getDefault')->will($test->returnValueMap(self::prepareDefaultData())); } if ($setActive) { $mockObject->expects($test->any())->method('getActive')->will($test->returnValue(self::$data[$setActive])); } 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; }
private function createUndeclaredMethods() { foreach (array_keys($this->originClassMethods) as $originalMethodName) { if (false == array_key_exists($originalMethodName, $this->mockMethods)) { $method = $this->mock->expects($this->testCase->any()); $method->method($originalMethodName); $method->will($this->testCase->throwException(new UndeclaredMethodInvocationException($originalMethodName))); } } }
public static function SetUpForFunctionalTests(\PHPUnit_Framework_TestCase &$test) { $context = new ApiContext(); $context->setConfig(array('mode' => 'sandbox', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'FINE', 'validation.level' => 'warning')); PayPalCredentialManager::getInstance()->setCredentialObject(PayPalCredentialManager::getInstance()->getCredentialObject('acct1')); self::$mode = getenv('REST_MODE') ? getenv('REST_MODE') : 'mock'; if (self::$mode != 'sandbox') { // Mock PayPalRest Caller if mode set to mock $test->mockPayPalRestCall = $test->getMockBuilder('\\PayPal\\Transport\\PayPalRestCall')->disableOriginalConstructor()->getMock(); $test->mockPayPalRestCall->expects($test->any())->method('execute')->will($test->returnValue($test->response)); } }
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); }
/** * @param \PHPUnit_Framework_TestCase $test * @param string $class * @param \Closure $qbCallback * * @return EntityRepository */ public static function create(\PHPUnit_Framework_TestCase $test, $class, \Closure $qbCallback) { $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('from')->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('addSelect')->will($test->returnValue($qb)); $qb->expects($test->any())->method('leftJoin')->will($test->returnValue($qb)); $qbCallback($qb); $em = $test->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock(); $metadata = $test->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock(); $em->expects($test->any())->method('createQueryBuilder')->will($test->returnValue($qb)); return new $class($em, $metadata); }
public static function SetUpForFunctionalTests(\PHPUnit_Framework_TestCase &$test) { $configs = array('mode' => 'sandbox', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'FINE', 'validation.level' => 'log'); $test->apiContext = new ApiContext(new OAuthTokenCredential('AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS', 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL')); $test->apiContext->setConfig($configs); //PayPalConfigManager::getInstance()->addConfigFromIni(__DIR__. '/../../../sdk_config.ini'); //PayPalConfigManager::getInstance()->addConfigs($configs); PayPalCredentialManager::getInstance()->setCredentialObject(PayPalCredentialManager::getInstance()->getCredentialObject('acct1')); self::$mode = getenv('REST_MODE') ? getenv('REST_MODE') : 'mock'; if (self::$mode != 'sandbox') { // Mock PayPalRest Caller if mode set to mock $test->mockPayPalRestCall = $test->getMockBuilder('\\PayPal\\Transport\\PayPalRestCall')->disableOriginalConstructor()->getMock(); $test->mockPayPalRestCall->expects($test->any())->method('execute')->will($test->returnValue($test->response)); } }
/** * Retrieve mock of core translator model * * @return Mage_Core_Model_Translate|PHPUnit_Framework_MockObject_MockObject */ protected function _getTranslatorMock() { $translator = $this->_testObject->getMockBuilder('Mage_Core_Model_Translate')->disableOriginalConstructor()->setMethods(array('translate'))->getMock(); $translateCallback = function ($arguments) { $result = ''; if (is_array($arguments) && current($arguments) instanceof Mage_Core_Model_Translate_Expr) { /** @var Mage_Core_Model_Translate_Expr $expression */ $expression = array_shift($arguments); $result = vsprintf($expression->getText(), $arguments); } return $result; }; $translator->expects($this->_testObject->any())->method('translate')->will($this->_testObject->returnCallback($translateCallback)); return $translator; }
/** * @param array|\PHPUnit_Framework_MockObject_MockObject $post * @param array|\PHPUnit_Framework_MockObject_MockObject $files * @param array|\PHPUnit_Framework_MockObject_MockObject $query * * @return \PHPUnit_Framework_MockObject_MockObject */ public function getRequestMock($post = null, $files = null, $query = null) { $mockBuilder = new MockBuilder($this->testCase, 'Zend\\Http\\Request'); $mockBuilder->setMethods(['isPost', 'getPost', 'getFiles', 'getQuery']); $mockBuilder->disableOriginalConstructor(); $requestMock = $mockBuilder->getMock(); $isPost = !is_null($post) || !is_null($files); $requestMock->expects($this->testCase->any())->method('isPost')->willReturn($isPost); if (null !== $post) { $requestMock->expects($this->testCase->any())->method('getPost')->willReturn($post); } if (null !== $files) { $requestMock->expects($this->testCase->any())->method('getFiles')->willReturn($files); } if (null !== $query) { $requestMock->expects($this->testCase->any())->method('getQuery')->willReturn($query); } return $requestMock; }
/** * Create a new mock of the curlbuilder and return * the given filename as content * * @access public * @param PHPUnit_Framework_TestCase $instance * @return mock */ public static function create($instance) { $reflection = new \ReflectionMethod($instance, $instance->getName()); $doc_block = $reflection->getDocComment(); $responsefile = self::parseDocBlock($doc_block, '@responsefile'); $responsecode = self::parseDocBlock($doc_block, '@responsecode'); if (empty($responsecode)) { $responsecode = [201]; } if (empty($responsefile)) { $responsefile = [$instance->getName()]; } // Setup Curlbuilder mock $curlbuilder = $instance->getMockBuilder("\\DirkGroenen\\Pinterest\\Utils\\CurlBuilder")->getMock(); $curlbuilder->expects($instance->once())->method('create')->will($instance->returnSelf()); $curlbuilder->expects($instance->once())->method('execute')->will($instance->returnValue(file_get_contents(__DIR__ . '/../responses/' . (new \ReflectionClass($instance))->getShortName() . '/' . $responsefile[0] . ".json"))); $curlbuilder->expects($instance->any())->method('getInfo')->will($instance->returnValue($responsecode[0])); return $curlbuilder; }
/** * Creates an instance of the mock Joomla\Application\AbstractWebApplication object. * * @param array $options A associative array of options to configure the mock. * session => a mock session * class => an alternative class to mock (used for hybird legacy applications) * methods => an array of additional methods to mock * * @return object * * @since 1.0 */ public function createMockWeb($options = array()) { // Set expected server variables. if (!isset($_SERVER['HTTP_HOST'])) { $_SERVER['HTTP_HOST'] = 'localhost'; } // Collect all the relevant methods in JApplicationBase (work in progress). $methods = array('allowCache', 'appendBody', 'checkConnectionAlive', 'checkHeadersSent', 'close', 'clearHeaders', 'compress', 'detectRequestUri', 'doExecute', 'execute', 'fetchConfigurationData', 'get', 'getBody', 'getHeaders', 'getLogger', 'getSession', 'hasLogger', 'header', 'initialise', 'isSSLConnection', 'loadSystemUris', 'prependBody', 'redirect', 'respond', 'sendHeaders', 'set', 'setBody', 'setConfiguration', 'setHeader', 'setLogger', 'setSession'); // 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 = $this->test->getMock(isset($options['class']) ? $options['class'] : 'Joomla\\Application\\AbstractWebApplication', $methods, array(), '', true); // Mock a call to JApplicationWeb::getSession(). if (isset($options['session'])) { $mockObject->expects($this->test->any())->method('getSession')->will($this->test->returnValue($options['session'])); } Helper::assignMockCallbacks($mockObject, $this->test, array('appendBody' => array(is_callable(array($this->test, 'mockWebAppendBody')) ? $this->test : $this, 'mockWebAppendBody'), 'get' => array(is_callable(array($this->test, 'mockWebGet')) ? $this->test : $this, 'mockWebGet'), 'getBody' => array(is_callable(array($this->test, 'mockWebGetBody')) ? $this->test : $this, 'mockWebGetBody'), 'getHeaders' => array(is_callable(array($this->test, 'mockWebGetHeaders')) ? $this->test : $this, 'mockWebGetHeaders'), 'prependBody' => array(is_callable(array($this->test, 'mockWebPrependBody')) ? $this->test : $this, 'mockWebPrependBody'), 'set' => array(is_callable(array($this->test, 'mockWebSet')) ? $this->test : $this, 'mockWebSet'), 'setBody' => array(is_callable(array($this->test, 'mockWebSetBody')) ? $this->test : $this, 'mockWebSetBody'), 'setHeader' => array(is_callable(array($this->test, 'mockWebSetHeader')) ? $this->test : $this, 'mockWebSetHeader'))); return $mockObject; }
public static function SetUpForFunctionalTests(\PHPUnit_Framework_TestCase &$test) { $configs = array('mode' => 'sandbox', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => '../BlockCypher.log', 'log.LogLevel' => 'INFO', 'validation.level' => 'log'); // Replace these values by entering your own token by visiting https://accounts.blockcypher.com/ /** @noinspection SpellCheckingInspection */ $token = 'c0afcccdde5081d6429de37d16166ead'; /** @noinspection PhpUndefinedFieldInspection */ $test->apiContext = new ApiContext(new SimpleTokenCredential($token)); /** @noinspection PhpUndefinedFieldInspection */ $test->apiContext->setConfig($configs); //BlockCypherConfigManager::getInstance()->addConfigFromIni(__DIR__. '/../../../sdk_config.ini'); //BlockCypherConfigManager::getInstance()->addConfigs($configs); BlockCypherCredentialManager::getInstance()->setCredentialObject(BlockCypherCredentialManager::getInstance()->getCredentialObject('acct1')); self::$mode = getenv('REST_MODE') ? getenv('REST_MODE') : 'mock'; if (self::$mode != 'sandbox') { // Mock BlockCypherRest Caller if mode set to mock /** @noinspection PhpUndefinedFieldInspection */ $test->mockBlockCypherRestCall = $test->getMockBuilder('\\BlockCypher\\Transport\\BlockCypherRestCall')->disableOriginalConstructor()->getMock(); /** @noinspection PhpUndefinedFieldInspection */ $test->mockBlockCypherRestCall->expects($test->any())->method('execute')->will($test->returnValue($test->response)); } }
/** * 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; }
/** * Returns a matcher that matches when the method it is evaluated for * is executed zero or more times. * * @return PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount * @since Method available since Release 3.0.0 */ function any() { return PHPUnit_Framework_TestCase::any(); }
/** * Assigns mock values to methods. * * @param \PHPUnit_Framework_TestCase $test A test object. * @param \PHPUnit_Framework_MockObject_MockObject $mockObject The mock object. * @param array|\ArrayAccess $array An associative array of methods to mock with return values: * string (method name) => mixed (return value) * * @return void * * @since 1.0 */ public function assignMockReturns($test, $mockObject, $array) { foreach ($array as $method => $return) { $mockObject->expects($test->any())->method($method)->willReturn($return); } }
/** * @param $placeholderName * @return \PHPUnit_Framework_MockObject_MockObject | PlaceholderAbstract */ public static function getMockCustomPlaceholder($placeholderName) { $myPlaceholder = \PHPUnit_Framework_MockObject_Generator::getMockForAbstractClass('\\DbEasy\\Placeholder\\PlaceholderAbstract', [], '', true, true, true, ['getName']); $myPlaceholder->expects(\PHPUnit_Framework_TestCase::any())->method('getName')->will(\PHPUnit_Framework_TestCase::returnValue($placeholderName)); $myPlaceholder->expects(\PHPUnit_Framework_TestCase::any())->method('transformValue')->will(\PHPUnit_Framework_TestCase::returnCallback(function ($value) { if ($value === 'in1') { return 'out1'; } if ($value === 'in2') { return 'out2'; } if ($value === 'in3') { return 'out3'; } if ($value === 'in4') { return 'out4'; } if ($value === true) { return true; } if ($value === false) { return false; } if ($value === 0) { return 0; } if ($value === '') { return ''; } if ($value === 'skip_me_please') { return Database::SKIP_VALUE; } })); $myPlaceholder->expects(\PHPUnit_Framework_TestCase::any())->method('transformPlaceholder')->will(\PHPUnit_Framework_TestCase::returnCallback(function ($value, $nativePlaceholder) { if (!empty($nativePlaceholder)) { if ($value === 'skip_me_please') { return "SQL_PART_WITHOUT_PARAMS"; } return $nativePlaceholder; } if ($value === 'in1') { return '"out1"'; } if ($value === 'in2') { return '"out2"'; } if ($value === 'in3') { return '"out3"'; } if ($value === 'in4') { return '"out4"'; } if ($value === true) { return 'TRUE'; } if ($value === false) { return 'FALSE'; } if ($value === 0) { return '0'; } if ($value === '') { return '""'; } })); return $myPlaceholder; }
/** * @param \PHPUnit_Framework_TestCase $test * @param \Closure $qbCallback * @param $fields * * @return EntityManagerInterface */ public static function create(\PHPUnit_Framework_TestCase $test, \Closure $qbCallback, $fields) { $query = $test->getMockForAbstractClass('Doctrine\\ORM\\AbstractQuery', array(), '', false, true, true, array('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(array($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; }
/** * Assigns mock values to methods. * * @param \PHPUnit_Framework_MockObject_MockObject $mockObject The mock object. * @param \PHPUnit_Framework_TestCase $test The test. * @param array $array An associative array of methods to mock with return values:<br /> * string (method name) => mixed (return value) * * @return void * * @since 2.0 */ public static function assignMockReturns(\PHPUnit_Framework_MockObject_MockObject $mockObject, \PHPUnit_Framework_TestCase $test, $array) { foreach ($array as $method => $return) { $mockObject->expects($test->any())->method($method)->will($test->returnValue($return)); } }
/** * @return \PHPUnit_Framework_MockObject_MockObject|\LightSaml\Model\Metadata\EndpointReference */ public static function getEndpointReferenceMock(\PHPUnit_Framework_TestCase $test, Endpoint $endpoint) { $endpointReferenceMock = $test->getMockBuilder(\LightSaml\Model\Metadata\EndpointReference::class)->disableOriginalConstructor()->getMock(); $endpointReferenceMock->expects($test->any())->method('getEndpoint')->willReturn($endpoint); return $endpointReferenceMock; }