K
K
kirov_dima2014-04-01 11:49:13
PHPUnit
kirov_dima, 2014-04-01 11:49:13

How to organize testing of controllers in the MVC pattern using phpUnit?

There is a cabinet_conrtoller controller class with an index() method:

class cabinet_controller
{
    ...
    public function index()
    {
        ...
        $users = new users_model();
        $user = $users->get(array('id'=>$_SESSION['user_id']));
        ...
    }
    ...
}

Accordingly, I want to test it so that I don’t have to create an instance of the users_model model, but somehow “replace” it (so that I don’t have to connect to a real database and generally abstract from model classes in principle).
I read about mocks in phpUnit, but in all the examples, the generated mock is explicitly passed to the method of the class we are testing. Something along the lines of:
public function testIndex()
{
    $users_model = $this->getMock('users_model');
    $users_model->expects($this->any())
                ->method('get')
                ->will($this->returnValue(array(...));

    $cabinet_controller = new cabinet_controller();
    $cabinet_controller->index($users_model);
}

But what if the class instance is created in the method under test itself?
And in general, am I right in testing controllers this way?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question