CakePHP test behavior with mapped method

During the creation of OwnableBehavior I decided to use the existing $mapMethods property. It should map any method named isOwnedByXXX() to isOwnedBy() (link for documentation on this here )

Here is my OwnableBehavior code:

 class OwnableBehavior extends Model Behavior { public $mapMethods = array('/isOwnedBy(\w+)/' => 'isOwnedBy'); public function isOwnedBy(Model $model, $type, $id, Model $userModel, $userId) { // Method is currently empty } } 

Here is the TestCase code:

 class OwnableBehaviorTest extends CakeTestCase { public function testIsOwned() { $TestModel = new Avatar(); $TestModel->Behaviors->attach('Ownable'); $result = $TestModel->Behaviors->Ownable->isOwnedByUser( $TestModel, 1, new User(), 1); $this->assertTrue($result); } } 

When I run the test, I get this error:

  Call to undefined method OwnableBehavior::isOwnedByUser() 

If I change the method call to isOwnedBy($TestModel, 'user', 1, new User(), 1); This works, so for some reason, the methods displayed do not work during the unit test. I tested the associated methods in the controller and I am not getting errors.

I wondered if there was any way I was loading behavior into a model. I could not find any documentation in the cookbook on how to properly test behavior, for example, with components, helpers, etc. Therefore, I used the same methods that use the Core Behavior tests (Found in Cake/Test/Case/Model/Behavior/ ).

I thought maybe this could be due to the fact that I was rewriting the ModelBehavior::setup() method, but I tried to add parent::setup($model, $settings) at the beginning of the installation method, and I still get the same a mistake. I do not rewrite other ModelBehavior methods.

I think I could just use the OwnableBehavior::isOwnedBy() method, but I'd really like to know if I can make the displayed methods work during the unit test.

+2
source share
1 answer

The solution I found replaces this line:

 $result = $TestModel->Behaviors->Ownable->isOwnedByUser(...); 

with:

 $result = $TestModel->isOwnedByUser(...); 

So, this is just a case of using it more, as in an application, calling a behavior method directly from the model. I don't know if this breaks down the idea of ​​unit test and does it more in integration testing.

+2
source

Source: https://habr.com/ru/post/957572/


All Articles