简体   繁体   English

如何在Yii中模拟ActiveRecord对象?

[英]How do I mock an ActiveRecord object in Yii?

In Yii I want to perform some unit tests on a class that uses ActiveRecord objects. 在Yii中,我想对使用ActiveRecord对象的类执行一些单元测试。 For example, I have a Translation ActiveRecord. 例如,我有一个翻译ActiveRecord。 When I try to create a mock object for it I get an error. 当我尝试为其创建模拟对象时,出现错误。

In my test I have the line: 在我的测试中,我的代码是:

$translation = $this->getMock("Translation");

And then I get this error when I run my test: 然后在运行测试时出现此错误:

PHPUnit 3.7.30 by Sebastian Bergmann.

Configuration read from /Users/riverstyx/Sites/protected/tests/phpunit.xml

E.

Time: 1.27 seconds, Memory: 6.25Mb

There was 1 error:

1) TranslationManagerTest::testCreateNewTranslation
Trying to get property of non-object

/Users/riverstyx/yii/framework/db/ar/CActiveRecord.php:79
/Users/riverstyx/Sites/protected/tests/unit/TranslationManagerTest.php:8

FAILURES!
Tests: 2, Assertions: 0, Errors: 1

I understand the concept of using fixtures in Yii however I don't want to have to rely on a database to do my testing. 我了解在Yii中使用固定装置的概念,但是我不想依靠数据库来进行测试。 We use MySQL in production, so creating a temporary in-memory SQLITE database seems weird because it doesn't match our actual MySQL environment and also there are some syntax nuances (ie. UTC_TIMESTAMP() doesnt exist in SQLITE). 我们在生产中使用MySQL,因此创建一个临时的内存中SQLITE数据库似乎很奇怪,因为它与我们的实际MySQL环境不匹配,并且在语法上也有些细微差别(即,在SQLITE中不存在UTC_TIMESTAMP())。

Ideally (as with all unit tests I guess), I want to test my TranslationManager class in isolation from the active record. 理想情况下(与我猜测的所有单元测试一样),我想与活动记录隔离地测试我的TranslationManager类。

Any help would be appreciated :) 任何帮助,将不胜感激 :)

Figured it out... 弄清楚了...

$this->getMockBuilder("Translation")
     ->setMethods(array("getIsNewRecord", "save"))
     ->disableOriginalConstructor()
     ->getMock();

Where "Translation" is the name of my active record model. 其中“翻译”是我的活动记录模型的名称。 You MUST use setMethods to identify the methods you're going to be mocking so that the rest of the methods belonging to the active record will remain intact. 您必须使用setMethods来确定要模拟的方法,以便属于活动记录的其余方法将保持不变。 This is important so that the default __get and __set magic methods will still work properly. 这很重要,这样默认的__get和__set魔术方法仍然可以正常工作。

"disableOriginalConstructor" is required to properly construct the activerecord object 需要“ disableOriginalConstructor”才能正确构造activerecord对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM