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 = 'example@example.com';

        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?



1.4k

if(true)?



9.4k

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?



5.5k

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 = 'example@example.com';

        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