To define a TestCase 1) Implement a subclass of PHPUnit_Framework_TestCase. 2) Define instance variables that store the state of the fixture. 3) Initialize the fixture state by overriding setUp(). 4) Clean-up after a test by overriding tearDown(). Each test runs in its own fixture so there can be no side effects among test runs. Here is an example: value1 = 2; $this->value2 = 3; } } ?> For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling assert with a boolean. assertTrue($this->value1 + $this->value2 == 5); } ?>
Author: Sebastian Bergmann (sb@sebastian-bergmann.de)
Inheritance: extends PHPUnit_Framework_Assert, implements PHPUnit_Framework_Test, implements PHPUnit_Framework_SelfDescribing
Beispiel #1
0
 public static function getTestFileName(\PHPUnit_Framework_TestCase $testCase)
 {
     if ($testCase instanceof TestCase\Interfaces\Descriptive) {
         return $testCase->getFileName();
     }
     return (new \ReflectionClass($testCase))->getFileName();
 }
Beispiel #2
0
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testMerge()
 {
     $fieldData = $this->createFieldData();
     $fieldMetadataData = $this->createFieldMetadata();
     $entityData = $this->createEntityData();
     $masterEntity = new EntityStub(1);
     $sourceEntity = new EntityStub(2);
     $collectionItem1 = new CollectionItemStub(1);
     $collectionItem2 = new CollectionItemStub(2);
     $masterEntity->addCollectionItem($collectionItem1);
     $sourceEntity->addCollectionItem($collectionItem2);
     $entities = [$masterEntity, $sourceEntity];
     $relatedEntities = [$collectionItem1, $collectionItem2];
     $fieldData->expects($this->once())->method('getEntityData')->will($this->returnValue($entityData));
     $fieldData->expects($this->once())->method('getMetadata')->will($this->returnValue($fieldMetadataData));
     $entityData->expects($this->once())->method('getEntities')->will($this->returnValue($entities));
     $entityData->expects($this->once())->method('getMasterEntity')->will($this->returnValue($masterEntity));
     $this->doctrineHelper->expects($this->any())->method('getEntityIdentifierValue')->will($this->returnCallback(function ($value) {
         return $value->getId();
     }));
     $fieldDoctrineMetadata = $this->createDoctrineMetadata();
     $fieldDoctrineMetadata->expects($this->any())->method('getFieldName')->will($this->returnValue('field_name'));
     $fieldMetadataData->expects($this->any())->method('getDoctrineMetadata')->will($this->returnValue($fieldDoctrineMetadata));
     $fieldMetadataData->expects($this->any())->method('getFieldName')->will($this->returnValue('collection'));
     $fieldMetadataData->expects($this->any())->method('has')->will($this->returnValue(true));
     $fieldMetadataData->expects($this->any())->method('get')->will($this->returnValue('setEntityStub'));
     $repository = $this->getMockBuilder('Doctrine\\Common\\Persistence\\ObjectRepository')->disableOriginalConstructor()->getMock();
     $this->doctrineHelper->expects($this->any())->method('getEntityRepository')->will($this->returnValue($repository));
     $repository->expects($this->any())->method('findBy')->will($this->returnCallback(function ($values) use($relatedEntities) {
         return [$relatedEntities[$values['field_name']->getId() - 1]];
     }));
     $this->strategy->merge($fieldData);
     $this->assertEquals($masterEntity, $collectionItem1->getEntityStub());
     $this->assertEquals($masterEntity, $collectionItem2->getEntityStub());
 }
Beispiel #3
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;
 }
 /**
  * @dataProvider callbackDataProvider
  *
  * @param string $expectedMessage
  * @param string $expectedMethod
  * @param string $exceptionClass
  * @throws
  */
 public function testMainFlow($expectedMessage, $expectedMethod, $exceptionClass)
 {
     $this->_testCase->expects($this->any())->method($expectedMethod)->with($this->stringStartsWith($expectedMessage));
     $this->_invoker->__invoke(function () use($exceptionClass) {
         throw new $exceptionClass('Some meaningful message.');
     }, [[0]]);
 }
 public static function check(\PHPUnit_Framework_TestCase $test, SSODescriptor $descriptor, array $expectedNameIdFormats)
 {
     $test->assertCount(count($expectedNameIdFormats), $descriptor->getAllNameIDFormats());
     foreach ($expectedNameIdFormats as $nameIdFormat) {
         $test->assertTrue($descriptor->hasNameIDFormat($nameIdFormat));
     }
 }
Beispiel #6
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 static function check(\PHPUnit_Framework_TestCase $test, $name, $display, $url, Organization $organization = null)
 {
     $test->assertNotNull($organization);
     $test->assertEquals($name, $organization->getOrganizationName());
     $test->assertEquals($display, $organization->getOrganizationDisplayName());
     $test->assertEquals($url, $organization->getOrganizationURL());
 }
Beispiel #8
0
 /**
  * Test a factory.
  *
  * @param  string $className
  * @return void
  */
 public function testFactory($classname, array $requiredOptions, array $options)
 {
     // Test that the factory does not allow a scalar option.
     try {
         $classname::factory(0);
         $this->testCase->fail('An expected exception was not thrown');
     } catch (\Zend\Mvc\Router\Exception\InvalidArgumentException $e) {
         $this->testCase->assertContains('factory expects an array or Traversable set of options', $e->getMessage());
     }
     // Test required options.
     foreach ($requiredOptions as $option => $exceptionMessage) {
         $testOptions = $options;
         unset($testOptions[$option]);
         try {
             $classname::factory($testOptions);
             $this->testCase->fail('An expected exception was not thrown');
         } catch (\Zend\Mvc\Router\Exception\InvalidArgumentException $e) {
             $this->testCase->assertContains($exceptionMessage, $e->getMessage());
         }
     }
     // Create the route, will throw an exception if something goes wrong.
     $classname::factory($options);
     // Try the same with an iterator.
     $classname::factory(new ArrayIterator($options));
 }
 /**
  * @param TblCronTask[] $cronTasks
  * @return \Trovit\CronManagerBundle\Repository\TblCronTaskRepository|\PHPUnit_Framework_MockObject_MockObject
  */
 public function getReadMock(array $cronTasks)
 {
     $mock = $this->getBasicMock();
     $mock->expects($this->_testCase->once())->method('findAll')->willReturn($cronTasks);
     $mock->expects($this->_testCase->once())->method('getActiveCronTasks')->willReturn($cronTasks);
     return $mock;
 }
 protected function buildStub($will)
 {
     if (!is_object($will) || !$will instanceof PHPUnit_Framework_MockObject_Stub) {
         $will = $this->testCase->returnValue($this->buildIfValueIsABuilder($will));
     }
     return $will;
 }
 /**
  * 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_TestCase $testCase
  */
 private function setUpContext(\PHPUnit_Framework_TestCase $testCase)
 {
     $annotations = $testCase->getAnnotations();
     if (isset($annotations['method'][$this->annotationName])) {
         $this->callMethods($testCase, $annotations['method'][$this->annotationName]);
     }
 }
Beispiel #13
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);
 }
Beispiel #14
0
 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;
 }
Beispiel #15
0
 protected function doDelete(RecordInterface $record, Version $version)
 {
     $this->testCase->assertEquals(8, $this->pathParameters->getProperty('fooId'));
     $this->testCase->assertEmpty($this->pathParameters->getProperty('bar'));
     $this->testCase->assertEquals(1, $record->getId());
     return array('success' => true, 'message' => 'You have successful delete a record');
 }
Beispiel #16
0
 /**
  * Assert that the given number of SQL queries were made.
  * 
  * @param integer $queryCount
  */
 public function assertTotalNumQueries($queryCount, $msg = null)
 {
     if (!$msg) {
         $msg = "Failed asserting that " . (int) $queryCount . " SQL queries were made.";
     }
     $this->_test->assertEquals($queryCount, $this->_profiler->getTotalNumQueries(), $msg);
 }
 /**
  * Register fixture components
  *
  * @param \PHPUnit_Framework_TestCase $test
  */
 private function registerComponents(\PHPUnit_Framework_TestCase $test)
 {
     $annotations = $test->getAnnotations();
     $componentAnnotations = [];
     if (isset($annotations['class'][self::ANNOTATION_NAME])) {
         $componentAnnotations = array_merge($componentAnnotations, $annotations['class'][self::ANNOTATION_NAME]);
     }
     if (isset($annotations['method'][self::ANNOTATION_NAME])) {
         $componentAnnotations = array_merge($componentAnnotations, $annotations['method'][self::ANNOTATION_NAME]);
     }
     if (empty($componentAnnotations)) {
         return;
     }
     $componentAnnotations = array_unique($componentAnnotations);
     $reflection = new \ReflectionClass(self::REGISTRAR_CLASS);
     $paths = $reflection->getProperty(self::PATHS_FIELD);
     $paths->setAccessible(true);
     $this->origComponents = $paths->getValue();
     $paths->setAccessible(false);
     foreach ($componentAnnotations as $fixturePath) {
         $fixturesDir = $this->fixtureBaseDir . '/' . $fixturePath;
         if (!file_exists($fixturesDir)) {
             throw new \InvalidArgumentException(self::ANNOTATION_NAME . " fixture '{$fixturePath}' does not exist");
         }
         $iterator = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fixturesDir, \FilesystemIterator::SKIP_DOTS)), '/^.+\\/registration\\.php$/');
         /**
          * @var \SplFileInfo $registrationFile
          */
         foreach ($iterator as $registrationFile) {
             require $registrationFile->getRealPath();
         }
     }
 }
 /**
  * @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 $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;
 }
 public function assertOnlyDeprecatedErrors(array $deprecationMessages)
 {
     $this->testCase->assertSame(count($deprecationMessages), $this->getCount());
     $this->testCase->assertSame(count($deprecationMessages), $this->getDeprecatedCount());
     foreach ($deprecationMessages as $index => $message) {
         $this->testCase->assertSame($message, $this->getMessage($index));
     }
 }
 public static function checkCertificateCN(\PHPUnit_Framework_TestCase $test, $use, $cn, KeyDescriptor $kd = null)
 {
     $test->assertNotNull($kd);
     $test->assertEquals($use, $kd->getUse());
     $test->assertNotEmpty($kd->getCertificate()->getData());
     $crt = openssl_x509_parse($kd->getCertificate()->toPem());
     $test->assertEquals($cn, $crt['subject']['CN']);
 }
Beispiel #22
0
 /**
  * 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;
 }
 public static function assertErrorMessages(TestCase $testCase, FormErrorSequence $formErrorSequence, array $expectedMessages)
 {
     $actualMessages = [];
     foreach ($formErrorSequence as $formError) {
         $actualMessages[$formError->getKey()] = $formError->getMessage();
     }
     $testCase->assertSame($expectedMessages, $actualMessages);
 }
Beispiel #25
0
 /**
  * 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;
 }
 public static function assertErrorMessages(TestCase $testCase, ValidationResult $validationResult, array $expectedMessages)
 {
     $actualMessages = [];
     foreach ($validationResult->getValidationErrors() as $validationError) {
         $actualMessages[$validationError->getMessage()] = $validationError->getArguments();
     }
     $testCase->assertSame($expectedMessages, $actualMessages);
 }
Beispiel #27
0
function mockFileWriter(PHPUnit_Framework_TestCase $testcase, File $file)
{
    $in = $testcase->getMockForAbstractClass(FileWriter::class, [$file]);
    $in->method('write')->will($testcase->returnCallback(function ($data) {
        return strlen($data);
    }));
    return $in;
}
 /**
  * Checks if deployment configuration has been changed by a test
  *
  * Changing deployment configuration violates isolation between tests, so further tests may become broken.
  * To fix this issue, find out why this test changes deployment configuration.
  * If this is intentional, then it must be reverted to the previous state within the test.
  * After that, the application needs to be wiped out and reinstalled.
  *
  * @param \PHPUnit_Framework_TestCase $test
  * @return void
  */
 public function endTest(\PHPUnit_Framework_TestCase $test)
 {
     $config = $this->reader->load();
     if ($this->config != $config) {
         $error = "\n\nERROR: deployment configuration is corrupted. The application state is no longer valid.\n" . 'Further tests may fail.' . " This test failure may be misleading, if you are re-running it on a corrupted application.\n" . $test->toString() . "\n";
         $test->fail($error);
     }
 }
Beispiel #29
0
 /**
  * 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;
 }
Beispiel #30
0
function mockFileOutputStream(PHPUnit_Framework_TestCase $testcase, File $file)
{
    $in = $testcase->getMockForAbstractClass('BapCat\\Interfaces\\Persist\\FileOutputStream', [$file]);
    $in->method('write')->will($testcase->returnCallback(function ($data) {
        return strlen($data);
    }));
    return $in;
}