/**
  * @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;
 }
Exemplo n.º 2
0
 /**
  * @param \ReflectionParameter $parameter
  * @return mixed
  */
 private function getArgumentMock(\ReflectionParameter $parameter)
 {
     if ($parameter->getClass() !== null) {
         return $this->testCase->getMockBuilder($parameter->getClass()->getName())->disableOriginalConstructor()->getMock();
     }
     throw new \Mocktainer\UnmockableMethodArgumentException($parameter->getDeclaringClass()->getName(), $parameter->getDeclaringFunction()->getName(), $parameter->getName());
 }
 public function getMock()
 {
     $mock = $this->testCase->getMockBuilder('stdClass')->setMethods($this->functions)->setMockClassName('PHPUnit_Extension_FunctionMocker_' . uniqid())->getMock();
     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;
 }
Exemplo n.º 4
0
 /**
  * @param string $className
  * @param string $argumentName
  * @param \ReflectionParameter $parameter
  * @return mixed
  */
 private function getArgumentMock(string $className, string $argumentName, \ReflectionParameter $parameter)
 {
     if ($parameter->getClass() !== null) {
         return $this->testCase->getMockBuilder($parameter->getClass()->name)->disableOriginalConstructor()->getMock();
     }
     throw new \Mocktainer\UnmockableConstructorArgumentException($className, $argumentName);
 }
 /**
  * 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];
 }
 /**
  * @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);
 }
Exemplo n.º 7
0
 /**
  * Returns the mock object.
  * @return \PHPUnit_Framework_MockObject_MockObject
  */
 public function getMock()
 {
     $mock = $this->testCase->getMockBuilder('stdClass')->setMethods($this->functions)->setMockClassName('BluePsyduckTests_MultiCurl_Assets_FunctionMocker_' . uniqid())->getMock();
     foreach ($this->functions as $function) {
         if (!isset(self::$mockedFunctions[$this->namespace][$function])) {
             $code = $this->generateCode($this->namespace, $function);
             eval($code);
             self::$mockedFunctions[$this->namespace][$function] = $function;
         }
     }
     self::$currentMocks[$this->namespace] = $mock;
     return $mock;
 }
Exemplo n.º 8
0
 public function getPHPUnitMockObjectFor($className, array $methods)
 {
     $rc = new \ReflectionClass($className);
     $mockObject = null;
     if ($rc->isInterface()) {
         $mockObject = $this->testCase->getMockBuilder($className)->getMock();
     } elseif ($rc->isAbstract()) {
         $mockObject = $this->testCase->getMockBuilder($className)->disableOriginalConstructor()->setMethods($methods)->getMockForAbstractClass();
     } elseif ($rc->isTrait()) {
         $mockObject = $this->testCase->getMockBuilder($className)->disableOriginalConstructor()->setMethods($methods)->getMockForTrait();
     } else {
         $mockObject = $this->testCase->getMockBuilder($className)->disableOriginalConstructor()->disableOriginalClone()->disableArgumentCloning()->disallowMockingUnknownTypes()->getMock();
     }
     return $mockObject;
 }
Exemplo n.º 9
0
 /**
  * @param \PHPUnit_Framework_TestCase $testCase
  * @param array $results
  * @return XmlReader
  */
 public function getReaderMock(\PHPUnit_Framework_TestCase $testCase, array $results)
 {
     $result = new PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls(array_merge($results, []));
     $reader = $testCase->getMockBuilder('\\DataSource\\XmlReader')->disableOriginalConstructor()->getMock();
     $reader->expects(static::any())->method('getRows')->will($result);
     return $reader;
 }
 /**
  * @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;
 }
Exemplo n.º 11
0
 /**
  * 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;
 }
Exemplo n.º 12
0
 public static function getMysqli(\PHPUnit_Framework_TestCase $testCase)
 {
     $mysqli = $testCase->getMockBuilder('\\mysqli')->disableOriginalConstructor()->getMock();
     $mysqli->method('real_escape_string')->will($testCase->returnCallback(function ($v) {
         return addcslashes($v, "\"\n\r\\'");
         // not safe implementation!!!
     }));
     return $mysqli;
 }
Exemplo n.º 13
0
 /**
  * Retrieve mock of core translator model
  *
  * @param string $className
  * @return \Magento\Framework\TranslateInterface|\PHPUnit_Framework_MockObject_MockObject
  */
 protected function _getTranslatorMock($className)
 {
     $translator = $this->_testObject->getMockBuilder($className)->disableOriginalConstructor()->getMock();
     $translateCallback = function ($arguments) {
         return is_array($arguments) ? vsprintf(array_shift($arguments), $arguments) : '';
     };
     $translator->expects($this->_testObject->any())->method('translate')->will($this->_testObject->returnCallback($translateCallback));
     return $translator;
 }
Exemplo n.º 14
0
function mockDriver(PHPUnit_Framework_TestCase $testcase, $exists = true)
{
    $driver = $testcase->getMockBuilder('BapCat\\Interfaces\\Persist\\Driver')->getMockForAbstractClass();
    $driver->method('exists')->willReturn($exists);
    $driver->method('size')->willReturn(100);
    $driver->method('isLink')->willReturn(true);
    $driver->method('isReadable')->willReturn(true);
    $driver->method('isWritable')->willReturn(true);
    return $driver;
}
Exemplo n.º 15
0
function mockLocalDriver(PHPUnit_Framework_TestCase $testcase, $root)
{
    $driver = $testcase->getMockBuilder(LocalDriver::class)->setConstructorArgs([$root])->setMethods(['instantiateFile', 'instantiateDir'])->getMockForAbstractClass();
    $driver->method('instantiateFile')->will($testcase->returnCallback(function ($path) use($driver) {
        return new LocalFile($driver, $path);
    }));
    $driver->method('instantiateDir')->will($testcase->returnCallback(function ($path) use($driver) {
        return new LocalDirectory($driver, $path);
    }));
    return $driver;
}
Exemplo n.º 16
0
 /**
  * Creates and instance of the mock JDatabase object.
  *
  * @param   \PHPUnit_Framework_TestCase  $test        A test object.
  * @param   string                       $nullDate    A null date string for the driver.
  * @param   string                       $dateFormat  A date format for the driver.
  *
  * @return  object
  *
  * @since   1.0
  */
 public static function create(\PHPUnit_Framework_TestCase $test, $nullDate = '0000-00-00 00:00:00', $dateFormat = 'Y-m-d H:i:s')
 {
     // Collect all the relevant methods in JDatabase.
     $methods = array('connect', 'connected', 'disconnect', 'dropTable', 'escape', 'execute', 'fetchArray', 'fetchAssoc', 'fetchObject', 'freeResult', 'getAffectedRows', 'getCollation', 'getConnectors', 'getDateFormat', '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->getMockBuilder('\\Joomla\\Database\\DatabaseDriver')->setConstructorArgs(array(array()))->setMethods($methods)->getMock();
     // Mock selected methods.
     TestHelper::assignMockReturns($mockObject, $test, array('getNullDate' => $nullDate, 'getDateFormat' => $dateFormat));
     TestHelper::assignMockCallbacks($mockObject, $test, 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;
 }
Exemplo n.º 17
0
function mockDriver(PHPUnit_Framework_TestCase $testcase, $exists = true)
{
    $driver = $testcase->getMockBuilder(Driver::class)->getMockForAbstractClass();
    $driver->method('exists')->willReturn($exists);
    $driver->method('size')->willReturn(100);
    $driver->method('isLink')->willReturn(true);
    $driver->method('isReadable')->willReturn(true);
    $driver->method('isWritable')->willReturn(true);
    $driver->method('modified')->willReturn(0);
    return $driver;
}
Exemplo n.º 18
0
 /**
  * @param \Nethgui\Test\Tool\DB $db The database internal state object
  * @return \Nethgui\System\DatabaseInterface 
  */
 public static function getMockDatabase(\PHPUnit_Framework_TestCase $testcase, \Nethgui\Test\Tool\DB $db)
 {
     // Value is TRUE if the method modifies the database state.
     $databaseMethods = array('setProp' => TRUE, 'delProp' => TRUE, 'deleteKey' => TRUE, 'setKey' => TRUE, 'setType' => TRUE, 'getAll' => FALSE, 'getKey' => FALSE, 'getProp' => FALSE, 'getType' => FALSE);
     $dbMock = $testcase->getMockBuilder('Nethgui\\System\\EsmithDatabase')->disableOriginalConstructor()->setMethods(array_keys($databaseMethods))->getMock();
     $methodStub = new MockObject($db);
     foreach (array_keys($databaseMethods) as $method) {
         $dbMock->expects($testcase->any())->method($method)->will($methodStub);
     }
     return $dbMock;
 }
Exemplo n.º 19
0
 /**
  * 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;
 }
Exemplo n.º 20
0
 public static function createMockSession(\PHPUnit_Framework_TestCase $testCase)
 {
     $keyValueStore = new KeyValueStore();
     $sessionWrapper = $testCase->getMockBuilder(SessionWrapper::class)->getMock();
     $sessionWrapper->method('getValues')->willReturn([]);
     $sessionWrapper->method('sessionStart')->willReturn(true);
     $sessionWrapper->method('sessionName')->willReturn('Test Session');
     /** @var SessionWrapper $sessionWrapper */
     $session = new Session($sessionWrapper, $keyValueStore);
     $session->start();
     return $session;
 }
Exemplo n.º 21
0
 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));
     }
 }
Exemplo n.º 22
0
 /**
  * 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;
 }
Exemplo n.º 23
0
 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));
     }
 }
Exemplo n.º 24
0
 /**
  * Creates and instance of the mock DispatcherInterface 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 DispatcherInterface.
     $methods = array('addListener', 'dispatch', 'register', 'removeListener', 'trigger', 'test');
     // Create the mock.
     $mockObject = $test->getMockBuilder(DispatcherInterface::class)->setMethods($methods)->getMock();
     // Mock selected methods.
     $test->assignMockReturns($mockObject, array('test' => 'ok'));
     if ($defaults) {
         $test->assignMockCallbacks($mockObject, array('dispatch' => array(get_called_class(), 'mockDispatch'), 'addListener' => array(get_called_class(), 'mockRegister')));
     }
     return $mockObject;
 }
Exemplo n.º 25
0
 /**
  * Creates a mock for a given transfer (because of dynamic getters and setters)
  */
 public static function create($name, \PHPUnit_Framework_TestCase $phpunit)
 {
     $methods = array();
     $ref = new \ReflectionClass($name);
     foreach ($ref->getProperties() as $property) {
         $methods[] = 'get' . ucfirst($property->name);
         $methods[] = 'set' . ucfirst($property->name);
     }
     foreach ($ref->getMethods() as $method) {
         // do not mock array object methods to we can iterate these mocks
         if ($method->class === 'ArrayObject') {
             continue;
         }
         $methods[] = $method->name;
     }
     return $phpunit->getMockBuilder($name)->disableOriginalConstructor()->setMethods($methods)->getMock();
 }
Exemplo n.º 26
0
 /**
  * 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;
 }
Exemplo n.º 27
0
 /**
  * Constructor setting up object.
  *
  * @param string $function_name Name of the function to mock. Doesn't need to exist, might be newly created.
  * @param object $scope_object Object specifying the scope where the mocked function is used.
  */
 public function __construct($function_name, $scope_object)
 {
     if (!function_exists('runkit_function_redefine')) {
         trigger_error('Runkit is not installed.', E_USER_ERROR);
     }
     // APC doesn't quite like runkit.
     // When they work together, it might result dead process.
     if (function_exists('apc_clear_cache')) {
         apc_clear_cache();
     }
     $this->id = self::$next_id;
     $this->function_name = $function_name;
     $this->scope_object = $scope_object;
     $this->test_case = self::findTestCase();
     $this->mock_object = $this->test_case->getMockBuilder('Mock_' . str_replace('::', '__', $this->function_name) . '_' . $this->id)->disableAutoload()->setMethods(array('invoked'))->getMock();
     ++self::$next_id;
     self::$instances[$this->id] = $this;
     $this->createFunction();
 }
Exemplo n.º 28
0
 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 \PHPUnit_Framework_MockObject_MockObject|\Doctrine\ORM\EntityManager
  */
 public function getBasicMock()
 {
     return $this->_testCase->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
 }
 /**
  * @return \PHPUnit_Framework_MockObject_MockObject|\Trovit\CronManagerBundle\Model\CommandExecute
  */
 public function getBasicMock()
 {
     return $this->_testCase->getMockBuilder('Trovit\\CronManagerBundle\\Model\\CommandExecute')->disableOriginalConstructor()->getMock();
 }