TestCase.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace yiiunit\debug;
  3. use Yii;
  4. use yii\di\Container;
  5. use yii\helpers\ArrayHelper;
  6. /**
  7. * This is the base class for all yii framework unit tests.
  8. */
  9. abstract class TestCase extends \PHPUnit\Framework\TestCase
  10. {
  11. /**
  12. * Clean up after test.
  13. * By default the application created with [[mockApplication]] will be destroyed.
  14. */
  15. protected function tearDown()
  16. {
  17. parent::tearDown();
  18. $this->destroyApplication();
  19. }
  20. /**
  21. * Populates Yii::$app with a new application
  22. * The application will be destroyed on tearDown() automatically.
  23. * @param array $config The application configuration, if needed
  24. * @param string $appClass name of the application class to create
  25. */
  26. protected function mockApplication($config = [], $appClass = '\yii\console\Application')
  27. {
  28. new $appClass(ArrayHelper::merge([
  29. 'id' => 'testapp',
  30. 'basePath' => __DIR__,
  31. 'vendorPath' => dirname(__DIR__) . '/vendor',
  32. ], $config));
  33. }
  34. protected function mockWebApplication($config = [], $appClass = '\yii\web\Application')
  35. {
  36. new $appClass(ArrayHelper::merge([
  37. 'id' => 'testapp',
  38. 'basePath' => __DIR__,
  39. 'vendorPath' => dirname(__DIR__) . '/vendor',
  40. 'components' => [
  41. 'request' => [
  42. 'cookieValidationKey' => 'wefJDF8sfdsfSDefwqdxj9oq',
  43. 'scriptFile' => __DIR__ . '/index.php',
  44. 'scriptUrl' => '/index.php',
  45. ],
  46. ]
  47. ], $config));
  48. }
  49. /**
  50. * Destroys application in Yii::$app by setting it to null.
  51. */
  52. protected function destroyApplication()
  53. {
  54. Yii::$app = null;
  55. Yii::$container = new Container();
  56. }
  57. /**
  58. * Invokes object method, even if it is private or protected.
  59. * @param object $object object.
  60. * @param string $method method name.
  61. * @param array $args method arguments
  62. * @return mixed method result
  63. * @throws \ReflectionException
  64. */
  65. protected function invoke($object, $method, array $args = [])
  66. {
  67. $classReflection = new \ReflectionClass(get_class($object));
  68. $methodReflection = $classReflection->getMethod($method);
  69. $methodReflection->setAccessible(true);
  70. $result = $methodReflection->invokeArgs($object, $args);
  71. $methodReflection->setAccessible(false);
  72. return $result;
  73. }
  74. }