protected function buildStub($will) { if (!is_object($will) || !$will instanceof PHPUnit_Framework_MockObject_Stub) { $will = $this->testCase->returnValue($this->buildIfValueIsABuilder($will)); } return $will; }
/** * * @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; }
/** * 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 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 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; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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; }
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)); } }
/** * Build PHPUnit Mock in this method using $this->config for return values * Over-ride this for custom mock building * * @return \PHPUnit_Framework_MockObject_MockObject * @throws \Exception */ public function buildMock() { if (empty($this->className)) { throw new \Exception('Class name is required for default buildMock'); } $config = $this->config; $mock = $this->testCase->getMockBuilder($this->className)->disableOriginalConstructor()->getMock(); foreach ($config as $key => $returnValue) { $mock->method($key)->will($this->testCase->returnValue($returnValue)); } return $mock; }
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); }
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)); } }
/** * @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); }
/** * 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; }
/** * @param \PHPUnit_Framework_MockObject_MockObject $mock * @param array $expectedCalls * @param object|null $callbacksContext */ public static function addMockExpectedCalls(\PHPUnit_Framework_MockObject_MockObject $mock, array $expectedCalls, $callbacksContext = null) { $index = 0; if ($expectedCalls) { foreach ($expectedCalls as $expectedCall) { list($method, $arguments, $result) = $expectedCall; $methodExpectation = $mock->expects(\PHPUnit_Framework_TestCase::at($index++))->method($method); $methodExpectation = call_user_func_array(array($methodExpectation, 'with'), $arguments); if (is_string($result) && $callbacksContext && method_exists($callbacksContext, $result)) { $result = $callbacksContext->{$result}(); } $methodExpectation->will(\PHPUnit_Framework_TestCase::returnValue($result)); } } else { $mock->expects(\PHPUnit_Framework_TestCase::never())->method(\PHPUnit_Framework_TestCase::anything()); } }
/** * 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)); } }
/** @return array */ protected function parseMockMethodArgs($method, array $args) { $expects = TestCase::any(); $with = null; $will = TestCase::returnValue(null); if (count($args) == 1) { if ($args[0] instanceof InvokedRecorder || $args[0] instanceof InvokedAtIndex) { $expects = $args[0]; } else { $will = $args[0]; } } elseif (count($args) == 2) { if ($args[1] instanceof InvokedRecorder || $args[1] instanceof InvokedAtIndex) { if (is_array($args[0])) { list($with, $expects) = $args; } else { list($will, $expects) = $args; } } elseif (is_array($args[0])) { list($with, $will) = $args; } else { throw new \InvalidArgumentException(); } } elseif (count($args) == 3) { if (is_array($args[0]) && ($args[2] instanceof InvokedRecorder || $args[2] instanceof InvokedAtIndex)) { list($with, $will, $expects) = $args; } else { throw new \InvalidArgumentException(); } } if ($will instanceof \Exception) { $will = PhpUnitTestCase::throwException($will); } elseif (!$will instanceof Stub && !$will instanceof \Closure && !is_null($will)) { $will = PhpUnitTestCase::returnValue($will); } return array('method' => $method, 'expects' => $expects, 'with' => $with, 'will' => $will); }
/** * Retrieve specific mock of core resource model * * @return Mage_Core_Model_Resource_Resource|PHPUnit_Framework_MockObject_MockObject */ protected function _getResourceModelMock() { $resourceMock = $this->_testObject->getMock('Mage_Core_Model_Resource_Resource', array('getIdFieldName'), array(), '', false); $resourceMock->expects($this->_testObject->any())->method('getIdFieldName')->will($this->_testObject->returnValue('id')); return $resourceMock; }
/** * Get a command-object, which will return false on isSuccess * * @param string $sReturn * * @return \Testy\Util\Command */ public static function getFailure($sReturn = '') { $oCommandMock = self::getPlainMock($sReturn); $oCommandMock->expects(\PHPUnit_Framework_TestCase::any())->method('isSuccess')->will(\PHPUnit_Framework_TestCase::returnValue(false)); return $oCommandMock; }
/** * * * @param mixed $value * @return PHPUnit_Framework_MockObject_Stub_Return * @since Method available since Release 3.0.0 */ function returnValue($value) { return PHPUnit_Framework_TestCase::returnValue($value); }
/** * @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; }
public function invoke(\PHPUnit_Framework_MockObject_Invocation $invocation) { $returnData = parent::invoke($invocation); if (is_string($returnData)) { $returnData = array(0, $returnData); } $mock = clone $this->mock; if ($mock instanceof \PHPUnit_Framework_MockObject_MockObject) { $mock->expects(\PHPUnit_Framework_TestCase::any())->method('getOutput')->will(\PHPUnit_Framework_TestCase::returnValue($returnData[1])); $mock->expects(\PHPUnit_Framework_TestCase::any())->method('getOutputArray')->will(\PHPUnit_Framework_TestCase::returnValue(explode("\n", $returnData[1]))); $mock->expects(\PHPUnit_Framework_TestCase::any())->method('isExecuted')->will(\PHPUnit_Framework_TestCase::returnValue(TRUE)); $mock->expects(\PHPUnit_Framework_TestCase::any())->method('getExitStatus')->will(\PHPUnit_Framework_TestCase::returnValue($returnData[0])); $mock->expects(\PHPUnit_Framework_TestCase::never())->method('exec'); $mock->expects(\PHPUnit_Framework_TestCase::never())->method('addArgument'); $mock->expects(\PHPUnit_Framework_TestCase::never())->method('readOutput'); $mock->expects(\PHPUnit_Framework_TestCase::never())->method('kill'); $mock->expects(\PHPUnit_Framework_TestCase::never())->method('readExecutionState'); } return $mock; }
/** * 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)); } }
/** * Get a command-object, which will return false on isSuccess * * @return \Testy\Project */ public static function getDisabled() { $oMock = self::getPlainMock(); $oMock->expects(\PHPUnit_Framework_TestCase::any())->method('isEnabled')->will(\PHPUnit_Framework_TestCase::returnValue(false)); return $oMock; }
/** * @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; }