Skip to content

Commit

Permalink
Allow datasource access in constructors of mocked models.
Browse files Browse the repository at this point in the history
When mock objects are created from models that access their datasource
in the constructor, an exception would be raised for the missing default
datasource. By changing how configuration data is handled in the mock
creation we can avoid this issue and not reopen #4867

Refs #8225
  • Loading branch information
markstory committed Sep 13, 2016
1 parent d0041f1 commit 9d1fbb9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
26 changes: 26 additions & 0 deletions lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php
Expand Up @@ -39,6 +39,22 @@ class SecondaryPost extends Model {

}

/**
* ConstructorPost test stub.
*/
class ConstructorPost extends Model {

/**
* @var string
*/
public $useTable = 'posts';

public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->getDataSource()->cacheMethods = false;
}
}

/**
* CakeTestCaseTest
*
Expand Down Expand Up @@ -435,6 +451,16 @@ public function testGetMockForModelSecondaryDatasource() {
ConnectionManager::drop('test_secondary');
}

/**
* Test getMockForModel when the model accesses the datasource in the constructor.
*
* @return void
*/
public function testGetMockForModelConstructorDatasource() {
$post = $this->getMockForModel('ConstructorPost', array('save'), array('ds' => 'test'));
$this->assertEquals('test', $post->useDbConfig);
}

/**
* test getMockForModel() with plugin models
*
Expand Down
6 changes: 3 additions & 3 deletions lib/Cake/TestSuite/CakeTestCase.php
Expand Up @@ -718,13 +718,13 @@ protected function skipUnless($condition, $message = '') {
* @return Model
*/
public function getMockForModel($model, $methods = array(), $config = array()) {
$config += ClassRegistry::config('Model');
$defaults = ClassRegistry::config('Model');
unset($defaults['ds']);

list($plugin, $name) = pluginSplit($model, true);
App::uses($name, $plugin . 'Model');

$config = array_merge((array)$config, array('name' => $name));
unset($config['ds']);
$config = array_merge($defaults, (array)$config, array('name' => $name));

if (!class_exists($name)) {
throw new MissingModelException(array($model));
Expand Down

0 comments on commit 9d1fbb9

Please sign in to comment.