ModelAwareTraitTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since 3.0.0
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Test\TestCase\Model;
  15. use Cake\Model\ModelAwareTrait;
  16. use Cake\TestSuite\TestCase;
  17. /**
  18. * Testing stub.
  19. */
  20. class Stub {
  21. use ModelAwareTrait;
  22. public function setProps($name) {
  23. $this->_setModelClass($name);
  24. }
  25. }
  26. /**
  27. * ModelAwareTrait test case
  28. */
  29. class ModelAwareTraitTest extends TestCase {
  30. /**
  31. * Test set modelClass
  32. *
  33. * @return void
  34. */
  35. public function testSetModelClass() {
  36. $stub = new Stub();
  37. $this->assertNull($stub->modelClass);
  38. $stub->setProps('StubArticles');
  39. $this->assertEquals('StubArticles', $stub->modelClass);
  40. }
  41. /**
  42. * test loadModel()
  43. *
  44. * @return void
  45. */
  46. public function testLoadModel() {
  47. $stub = new Stub();
  48. $stub->setProps('Articles');
  49. $stub->modelFactory('Table', ['\Cake\ORM\TableRegistry', 'get']);
  50. $this->assertTrue($stub->loadModel());
  51. $this->assertInstanceOf('Cake\ORM\Table', $stub->Articles);
  52. $this->assertTrue($stub->loadModel('Comments'));
  53. $this->assertInstanceOf('Cake\ORM\Table', $stub->Comments);
  54. }
  55. /**
  56. * test alternate model factories.
  57. *
  58. * @return void
  59. */
  60. public function testModelFactory() {
  61. $stub = new Stub();
  62. $stub->setProps('Articles');
  63. $stub->modelFactory('Test', function($name) {
  64. $mock = new \StdClass();
  65. $mock->name = $name;
  66. return $mock;
  67. });
  68. $result = $stub->loadModel('Magic', 'Test');
  69. $this->assertTrue($result);
  70. $this->assertInstanceOf('\StdClass', $stub->Magic);
  71. $this->assertEquals('Magic', $stub->Magic->name);
  72. }
  73. /**
  74. * test MissingModelException being thrown
  75. *
  76. * @return void
  77. * @expectedException Cake\Model\Error\MissingModelException
  78. * @expectedExceptionMessage Model class "Magic" of type "Test" could not be found.
  79. */
  80. public function testMissingModelException() {
  81. $stub = new Stub();
  82. $stub->modelFactory('Test', function($name) {
  83. return false;
  84. });
  85. $stub->loadModel('Magic', 'Test');
  86. }
  87. }