Tuesday, September 13, 2011

phpunit Mock Objects

Since PHP is widely used as web application language , TDD ( Test Driven Development) is really important factor for web application development. All other popular languages which used *unit for testing classes and packages.

I'm really thanks to Sebastian Bergmann who introduce phpunit for PHP web application testing.


Web Application structured with mulity layers like DAO , Service , Controllers and views . So its really helpful test layer by layer. If its DAO layer then test mainly involve with data base operations. but if It's in above layers then It's really need to mock below layers and tests. Then phpunit mock objects play a major role to decouple layers and tests .

Following example shows how to write test for each layer
Test DAO Layer
$countryDao 	= 	new CountryDAO();
$result		=	$countryDao->searchCountryByCode('UK');
$this->assertType('Country',$result);
$this->assertEquals('UK',$result->getCountryCode());
$this->assertEquals('United Kingdom',$result->getCountryName));
Test Service Layer 
$country = new Country();
$country->setCountryCode('UK');
$country->setCountryName('United Kingdom');
$countryDao	=	$this->getMock('CountryDAO'); 
			$this->redhatCountry->expects($this->any())
                       ->method('searchCountryByCode')
                       ->will($this->returnValue($country));
$result		=	$countryDao->searchCountryByCode('UK');
$this->assertType('Country',$result);
$this->assertEquals('UK',$result->getCountryCode());
$this->assertEquals('United Kingdom',$result->getCountryName));

No comments:

Post a Comment