[英]Creating a PHPUnit mocked model uses default database instead of test in CakePHP
I am testing a model in CakePHP 2 and have mocked a model like this: 我在CakePHP 2中测试一个模型并且模拟了这样的模型:
$this->User = $this->getMock('User', array(
'_saveUploadedFile',
'_removeUploadedFile',
));
$this->User->expects($this->any())
->method('_saveUploadedFile')
->with($data, Configure::read('App.myDirectory'), true);
->will($this->returnValue(true));
$this->User->expects($this->any())
->method('_removeUploadedFile')
->with($data, Configure::read('App.myDirectory'))
->will($this->returnValue(true));
Since any operation with the database raises the following error: 由于使用数据库的任何操作都会引发以下错误:
"Database table mock__user_b6241a4cs for model User was not found."
I redefined the model information: 我重新定义了模型信息:
$this->User->alias = 'User';
$this->User->useTable = 'users';
Now the test works well, but it's using the $default
database in database.php
instead of $test
. 现在测试运行良好,但它使用database.php中的
$default
database.php
而不是$test
。 What can be happening? 可能发生什么?
Why the database configuration for testing changes when using mocked objects? 使用模拟对象时,为什么测试的数据库配置会发生变化? Could it be related to database permissions that causes the mocked object not being able to create its custom tables?
是否与数据库权限相关,导致模拟对象无法创建自定义表?
Thanks! 谢谢!
I finally solved the problem by passing the correct parameters to the model constructor in getMock()
third agument: 我终于通过将正确的参数传递给
getMock()
第三个文章中的模型构造函数来解决问题:
$this->User = $this->getMock('User',
array('_saveUploadedFile', '_removeUploadedFile'),
array(false, 'users', 'test')
);
Applying what is said in Stubs section of PHPUnit documentation, this third argument indicates that I want to use the users
table and the test
datasource. 应用PHPUnit文档的Stubs部分中的内容,第三个参数表明我想使用
users
表和test
数据源。
I have to keep the redefinition of the alias
property though: 我必须保留
alias
属性的重新定义:
$this->User->alias = 'User';
because a simple $this->User->read(null, 1)
raises an error saying that 'User.a_column'
couldn't be found. 因为一个简单的
$this->User->read(null, 1)
引发一个错误,指出找不到'User.a_column'
。
Thanks to José Lorenzo . 感谢JoséLorenzo 。
I haven't encountered this specific problem before, but I'm curious if you've tried setting the specific connection you want. 我之前没有遇到过这个特定的问题,但是我很好奇你是否尝试过设置你想要的特定连接。 So the same way you set
alias
and useTable
: 所以你设置
alias
和useTable
方式相同:
$this->User->useDbConfig = 'test';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.