Unit Testing basic Controllers

Go To StackoverFlow.com

1

I have a number of simple controller classes that use Doctrine's entity manager to retrieve data and pass it to a view.

public function indexAction() {
    $pages = $this->em->getRepository('Model_Page')->findAll();
    $this->view->pages = $pages;
}

What exactly should we be testing here?

  • I could test routing on the action to ensure that's configured properly
  • I could potentially test that the appropriate view variables are being set, but this is cumbersome

The findAll() method should probably be in a repository layer which can be tested using mock data, but then this constitutes a different type of test and brings us back to the question of

What should we be testing as part of controller tests?
2012-04-05 19:39
by dianovich


1

Controller holds core logic for your application. Though simple "index" controller actions don't have any specific functions, those that verify/actively use data and generate viewmodels have pretty much the most functionality of the system.

For example, consider login form. Whenever the login data is posted, controller should validate login/password and return: 1) to index page whenever logins are good. Show welcome,{user} text. 2) to the login page saying that login is not found in db. 3) to the login page saying that password is not found in db.

These three types of outputs make perfect test cases. You should validate that correct viewmodels/views are being sent back to the client with the appropriate actions.

You shouldn't look at a controller like at something mysterious. It's just another code piece, and it's tested as any other code - any complicated logic that gives business-value to the user should be tested.

Also, I'd recommend using acceptance testing with framework like Cucumber to generate meaningful test cases.

2012-04-05 20:01
by Dmitry Reznik
Thanks Dmitriy. Acceptance testing would be very useful to ensure that the output generated in the view is correct. Quite like Behat with Mink http://docs.behat.org/cookbook/behatandmink.html#writing-your-first-web-featur - dianovich 2012-04-05 21:50
You're welcome : - Dmitry Reznik 2012-04-06 05:13


0

Probably the controller is the hardest thing to test, as it has many dependencies. In theory you should test it in full isolation, but as you already seen - it has no sense.

Probably you should start with functional or acceptance test. It tests your controller action in a whole. I agree with previous answer, that you should try acceptance testing tools. But Cucumber is for Ruby, for PHP you can try using Codeception. It makes tests simple and meaningful.

Also on a Codeception page there is an article on how to test sample controllers.

2012-04-10 21:51
by Davert
Ads