How to test and mock zend framework controllers using PHPUnit?

I try to use my controllers unit test, but every tutorial that I found on the Internet says that I should use $ this-> dispatch ("controller / action") to trigger a specific action that I want to test. But in doing so, I cannot mock data files or other calls to other methods.

To solve this problem, I tried to get an instance of the controller class, and then directly access the methods that I wanted to test, but when I do this, I get an error message:

Zend_Exception: Setting request object manually is not allowed 

I’m not even sure that this is the right approach, because I really don’t know how I will check how this happens.

My test case: http://pastie.org/1812717

My ControllerTestCase: http://pastie.org/1812722

Any help would be greatly appreciated. Thanks.

+4
source share
3 answers

You have two solutions:

  • Pseudo-unit testing (more similar to acceptance testing) with Zend_Test_PHPUnit_ControllerTestCase
  • Creating a new controller instance, transferring all the necessary dependencies (dispatcher, request, response, plugins, etc.).

Both of them actually require a dispatch process. Firstly, sending the application, and secondly, dispatching controllers.

See the manual and sample tests from the full Zend Framework.

Also look at the source code of the controller to see how dependencies are managed.

See also other SO messages about injecting dependencies into Zend Framework controllers.

+3
source

I would suggest that Zend_Test_PHPUnit_ControllerTestCase does not allow you to mock Requset and Response objects. I would go around it and just extend PHPUnit_Framework_TestCase. As I mentioned in another question, I am currently mocking controllers without any problems.

Here is an example of a test that works fine:

http://pastie.org/1816705

AbstractRestController is just a controller class that extends Zend_Controller_Action

+2
source

How is an instance of data (or other objects) created? Do you create it directly in the controller or capture it from the bootstrap / registry? If you are using the registry or bootstrap, put the layout in the / bootstrap registry.

If you directly create an instance in the controller, you will need to change your controller. Maybe there is a controller method for setting data mapping, and then there is another way to capture the data card, and if it is not installed, then create an instance. This allows your tests to introduce a layout.

I usually do not scoff at many classes when testing controllers - I want to test the entire application and its ability to display the page ... It seems that you are not testing records in the database, so why not use Zend_Test_PHPUnit_Db to set up an empty table for this test, and not mock the data handler so as not to return data?

+1
source

All Articles