We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Testing API

I have a question, lets say i have a small API, and one of API controllers do something like this:

<?php

class UserController extends \Phalcon\Mvc\Controller {
    public function indexAction() {
        $user = new User();
        $user->name = 'User';
        $user->email = '[email protected]';

        if (!$user->create()) {
           // Here may be some other logic for user save fail
           thow new \Exception('User create error');
        }
    }
}

How can i mock user instance to test logic of user creation fail?



2.1k

if(true)?



20.5k

if($user->create == false) { // Here may be some other logic for user save fail thow new \Exception('User create error'); }

create function return true or false;

Just have $user->create() return false in your mock object. I assume you've got a unit test suite you're testing with?



7.9k

you can mock User object, you have to refactor your code, You have to pass User object as dependency

<?php

class UserController extends \Phalcon\Mvc\Controller {
    public function indexAction(User $user) {
        $user->name = 'User';
        $user->email = '[email protected]';

        if (!$user->create()) {
           // Here may be some other logic for user save fail
           thow new \Exception('User create error');
        }
    }
}

Then you can mock object for user. You dont have to hit database when testing