Hippyjim
Hippyjim

Reputation: 2522

Unit test Yii Behaviors

I'm looking for a way to unit test Yii behaviors based on CActiveRecordBehavior.

As the behaviors concerned can be used with many models, I want to test them independently of any model, but I can't work out how to do it.

The Yii source gives a unit test of the CTimestampBehavior using a database table that's made especially for the test. I have a lot of behaviors to test and don't want to have to create a table for each one - can anyone suggest a better strategy for testing behaviors without dependency on a specific model or table? Maybe some way to "fake" a CActiveRecord model?

[edit] To clarify - I don't want my test to rely on a specific model or database table being present - I want to test the behavior only. And just to make things even more interesting, the behavior attaches to the onAfterConstruct event, so it would need to be applied to the fake model before construct!

Upvotes: 4

Views: 736

Answers (1)

ThomasVdBerge
ThomasVdBerge

Reputation: 8140

Depends on what you want to test.

I usually implement them like this:

private $_oBehavior
private $_oObject;
private $_oEvent

$this->_oObject   = Object::model()->findByPk(n1);
$this->_oEvent    = new CModelEvent($this->oJob);
$this->_oBehavior = new TestBehavior;
$this->_oBehavior->attach($this->_oEvent->sender);

$this->_oBehavior->afterSave($this->_oEvent);
// asserts

This way you can test all stuff that needs a model by instantiating it like an event. All stuff that don't need a model can also be tested like this.

Upvotes: 2

Related Questions