Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

In memory unit testing for ORM Models

I was thinking to write in memory unit tests for ORM.

Example.

I have table called users in db and have model with name users.

Now For tests I wants to store users data in memory in Array not in db table.

Do anyone have any good idea or any other suggesions for me ?

Thanks



5.9k

Hi,

unit test shouldn't hit database, your approach using array for data is correct.

avoid external process in unit testing, eg: database, email, calls external API

Thanks for the comment. Do you have any idea how can I achieve this in Palcon ORM ?

Thanks



5.9k

it depend on your application.

could you share some snippet in your controller or part of application that you want to test?

    <?php
        $di->set('usersRepository', array(
    'className' => 'Phalcon\Repositories\UsersRepository'
    ));

    $di->set('UsersController', array(
        'className' => 'UsersController',
        'arguments' => array(
            array('type' => 'service', 'name' => 'usersRepository')
        )
    ));

    class UsersController extends AbstractController
    {
      /**
       * @var Phalcon\Repositories\UsersRepository
       */
      private $usersRepository;

      /**
       * @param $usersRepository
       */
      public function __construct($usersRepository)
      {
          $this->usersRepository = $usersRepository;
      }

      public function registerAction($user)
      {
          $this->usersRepository->create($user);
      }

      public function listusersAction()
      {
          var_dump($this->usersRepository->findById(1));exit;
      }
    }


    class UsersRepository implements UsersRepositoryService
    {
        /**
         * @var Users
         */
        private $users;

        public function __construct()
        {
            $this->users = new Users();
        }

        public function create(array $user)
        {
            $this->users->save($user);
        }

        public function find()
        {

        }

        public function findById($id)
        {
            return Users::findFirst($id);
        }

        public function findByEmail($email)
        {

        }

        public function updateById($id)
        {

        }

    }

And my model is Users with basic fields like username, password etc.



5.9k
Accepted
answer

Then mock UsersRepository and mock method findById that return User Object so you don't need hit database.