[TYPO3-mvc] UnitTests for Controller

Jochen Rau jochen.rau at typoplanet.de
Mon Nov 30 03:53:30 CET 2009


Hi Dennis,

dennis ahrens wrote:
> in my case the controller is just calling some methods on a parser
> which build up a object and adds it to the repository.
> Looks like this:
>
> public function importAction($xmlFile) {
> 		$this->parser->loadXMLFile($xmlFile,'documenttemplate.xsd');
> 		if($this->parser->validate()) {
> 			$documentTemplate = $this->parser->convertIntoObject();
> 			$this->documentTemplateRepository->add($documentTemplate);
> 		}
> 	}
>
> do you think it's best practice to write tests for all service methods
> and don't write tests for the controller at all?

It's ok to write tests for the controller, although it contains very 
little logic. Here is an example of a test for an indexAction:

public function indexAction() {
	$this->view->assign('organizations',
		$this->organizationRepository->findAll());
}


class Tx_SjrOffers_Controller_OrganizationControllerTest extends 
Tx_Extbase_BaseTestCase {
	
	/**
	 * @test
	 */
	public function indexActionWorks() {
		$mockOrganizationRepository = 
$this->getMock('Tx_SjrOffers_Domain_Repository_OrganizationRepository', 
array('findAll'), array(), '', FALSE);		
	 
$mockOrganizationRepository->expects($this->once())->method('findAll')->will($this->returnValue(array('organization1', 
'organization2')));

		$mockView = $this->getMock('Tx_Fluid_Core_View_TemplateView', 
array('assign'), array(), '', FALSE);
	 
$mockView->expects($this->once())->method('assign')->with('organizations', 
array('organization1', 'organization2'));

		$mockController = 
$this->getMock($this->buildAccessibleProxy('Tx_SjrOffers_Controller_OrganizationController'), 
array('dummy'), array(), '', FALSE);
		$mockController->_set('organizationRepository', 
$mockOrganizationRepository);
		$mockController->_set('view', $mockView);
		$mockController->indexAction();
	}

}

Because of the numerous dependencies of the controller, you have to make 
usage of mocks. The most important line here is

$mockController=$this->getMock($this->buildAccessibleProxy
  ('Tx_SjrOffers_Controller_OrganizationController'), array('dummy'),
  array(), '', FALSE);

The argument array('dummy') ensures that every method will be 
implemented and not mocked. That's a little bit confusing, but otherwise 
the indexAction will be replaced by a mock method and won't do anything. 
The argument FALSE ensures that the constructor will not be invoked.

Regards
Jochen

-- 
Every nit picked is a bug fixed



More information about the TYPO3-project-typo3v4mvc mailing list