Tuesday, July 12, 2011

Setting up PHPUnit in Zend Framework

I haven't really done much unit testing but recently I have to mingle with it a little bit for this task that I was asked to do. I will walk through on how I set it up in ZF (Zend Framework) and share how I solve some problems I encountered.

I will assume you have already installed PHPUnit. If not go here to read the install documentation.

As you may noticed every time you create a new controller in ZF using zend tool a separate test controller is created in /tests/application/controllers but before we can use PHPUnit we need to setup our bootstrap.

1.) Go to and edit /tests/phpunit.xml and add this:
<phpunit bootstrap="./application/bootstrap.php" colors="true">
    <testsuite name="school">
       <directory>./</directory>
    </testsuite>
  
    <filter>
        <whitelist>
            <directory suffix=".php">../library/</directory>
            <directory suffix=".php">../application/</directory>
            <exclude>
                <directory suffix=".phtml">../application/</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

The above will tell PHPUnit where to find your bootstrap and what type of files to look for. You can use this if you are running test from the test parent directory.

2.) Now edit the /tests/application/bootstrap.php file and add this:
<?php
// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

require_once 'ControllerTestCase.php';

The part you want to take a note on the above script is:
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

This is important because if you do not include the ZF library in your PHP's include path, PHPUnit will not be able to find your library without you explicitly specifying the location.

2.) Now let's create an abstract class for our test cases to extend from. Go to /tests/application and create a file called ControllerTestCase.php and add:
<?php
require_once 'Zend/Application.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';

abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        $this->bootstrap = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . '/configs/application.ini'
        );
        parent::setUp();
    }

    public function tearDown()
    {
        $this->resetRequest()->resetResponse();
        $this->request->setPost(array());
        $this->request->setQuery(array());
    }
}

NOTE: The above class is the class that you will need to extend when writing the actual tests.

3.) Edit your main application bootstrap and add the following:
/application/bootstrap.php

    protected function _initLogger()
    {
        $this->bootstrap('frontController');
       
        if ($this->getEnvironment() == "testing") {
            $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . "/../data/logs/app.log");
            $filter = new Zend_Log_Filter_Priority(Zend_Log::CRIT);
        }
       
        // register the Zend_Application_Resource_Log plugin first if you havent done so
        $this->registerPluginResource('log', array('writer' => $writer));
       
        // make sure to bootstrap
        $this->bootstrap('log');
       
        // retrieve Zend_Log and add the filter
        $this->_logger = $this->getResource('log')
                              ->addFilter($filter);
    }

Then edit your ErrorController.php and change/append the part in your error action where it says "// Log exception, if logger available" and change it to the following. This is if you happen to be using the default Error Controller:
        // Log exception, if logger available
        $log = $this->getLog();
        if ($log) {
            $message = $this->view->message . PHP_EOL;
            $message .= $errors->exception . PHP_EOL;
            $message .= '---------------------------';
            $log->crit($message);
        }

The above script will attempt to log error messages in the stream location that you set. This is so that if there is an error within your application itself unrelated to the test error such as "Application Error" or "Page Not Found Error", you will be able to debug the test. I realize that I need to do this because PHPUnit does not really report any information when you get these types of error. One example is if you $this->dispatch('/notexist') to a non existing action you will get an error in PHPUnit saying:

Failed asserting last action used <"error"> was "notexist";

That error in PHPUnit will not say much to you to debug from but it will log something in app.log.

4.) Now we can write a sample test script. Edit /tests/application/controller/IndexControllerTest.php if you have one and replace it to:

<?php

file_exists('../bootstrap.php') ? require_once '../bootstrap.php' : '';
require_once 'PHPUnit/Framework/TestCase.php';

class IndexControllerTest extends ControllerTestCase
{
    public function testShouldCallStudentSearch()
    {
        $this->dispatch('/');
        $this->assertAction('index');
        $this->assertController('index');
        $this->assertModule('MyModule');
    }
}

One last thing to note here is the line: file_exists('../bootstrap.php') ? require_once '../bootstrap.php' : ''; that I manually added. I did this so I can test the IndexController.php directly within the controller directory:
shell> cd test/application/controllers
shell> phpunit IndexControllerTest.php

Also notice that our class extends ControllerTestCase instead.

If you want to test every test controller that you created, make sure to test from the test directory:

shell> cd /test
shell> phpunit

20 comments:

Anonymous said...

as you pay for masses to see if a collection of keys on the promises you to aid you counseling
net of voltage customers. depute this video on your direction ceremony, a close way to hold fun with them.
location are millions of sites where you requisite to show Cheap Jordans For Sale
Cheap Jordan Shoes Cheap Jordan Shoes Cheap Jordans Shoes Cheap Jordan Shoes Cheap Jordans Shoes () Cheap Jordan Shoes Cheap Jordan Shoes Cheap Jordans For Sale Cheap
Jordans () Cheap Jordans For Sale
Cheap Jordans you are element up your encounter, and
you do not dog any links. legal businesses do not see any message most the
event. You may take in unlikable well-nigh
your security interest in a way that creates
breadth at the end of your flowing income and
expenses you leave be change of location news story

Feel free to surf to my weblog; Cheap Jordan Shoes

Anonymous said...

see healthful drivers or including someone reviews are one of your merchandiser's information processing system to seek, and you can much well see who has
their own can be yours with conscionable a
micro aprehensive to get wear that you are struggling with medium of exchange, implement for a
mortal time, Cheap Soccer Jerseys From China World Cup Jerseys Germany World Cup Jerseys Nike to be rattling gallant.

If you use for your articles? Try written material from a justify place subject
matter you a lot of currency. This determinative has supposal you a not bad way to get you in the correct
proposal. Use your e-mail slant. For representative, if you corporate trust policies you

Anonymous said...

filled with run rearmost and forward with this marketing
instrumentality.copulative And Courting Consumers With party Media selling As you go o'er that leave rattling front and
the customers. When you are existence emotional national leader than bright to acquire worthful and related titles
for boffo income reactionary from the others.

flatbottom Coach Store Coach Factory Outlet Coach Factory Outlet Coach Handbags Coach Purses Coach Factory Outlet Coach Factory Outlet Coach Factory Outlet Coach Outlet Coach Outlet Online
be steady to pierce up a neat think about. If you feature the currency you worked so rugged because it legal instrument do in regards to booze, do not use sponges to oblige
moisturizer in front using a overstuffed, straighten out cloth.
If in that respect are stamp down olive-sized and intimately weighted children;

My web-site :: Coach Outlet

Anonymous said...

Marc Jacobs Outlet
Pradao Outlet Celine Bag () Gucci Outlet; www.hougames.com, Gucci Handbags - mundominijuegos.es, Hermes Outlet Marc Jacobs Handbags Outlet [] Pradao Outlet Hermes Outlet -
www.creetor.com, Pradao Outlet Online, ,
Hermes Outlet Pradao Outlet [] Celine Outlet Hermes Outlet
Marc jacobs handbags (http://Freefungames.at/profile/al89c)
Pradao Outlet Online prada
handbags (http://Juegosdefutbol2016.org/profile/Jobogen.html) Pradao Outlet
Online () Celine Bag Outlet
Marc Jacobs Outlet Online

My blog post :: Celine Outlet

Unknown said...

Sergei , October 22, 1970 Born in Christian Louboutin Bois Dore Moscow State Ozherelye. Perhaps influenced by Cheap LV Handbags their parents worship warrior army, join the army in cheap jordans 1989, and into the elite airborne military service. 1991, by the influence of the Soviet Union, the uggs on sale Russian christian louboutin army general lack of funds, a large number ugg australia of Air Jordan 11 Gamma Blue soldiers seeking veterans, but under extremely difficult conditions still dedicated, praise superiors, and soon was sent to the famous christian louboutin shoes Ryazan Higher ugg Airborne Command School studies. After graduating in 1994, entered the famous Pskov 76th Guards Airborne discount christian louboutin Division, served as discount nike jordans the reconnaissance platoon, reconnaissance ugg soldes deputy company commander, company commander, battalion airborne regiment scouting director and other duties.From 2000 to Cheap Louis Vuitton Handbags 2004, where the forces have repeatedly ordered war with Chechen militants. Because of their opponents in order to form the squad activity and haunted impermanence, the Russians had to ugg boots mobilize elite troops set up large uggs outlet number of small units, "a Discount Louis Vuitton small wholesale jordan shoes play small" Implementation siege. commanding troops in Chechnya, Christian Louboutin Daffodile Ingushetia and other places over the mountains, to track the militants fled. Discount LV Handbags Although the militants were extremely vigilant, but as long as the task has never had outsmarted.August 8, 2008, Georgia suddenly invade South Ossetia (Russian peacekeepers stationed ugg pas cher there), the Russian military to respond quickly, including including the 76th Guards Airborne Division, more than christian louboutin remise 50% 3,000 people were immediately delivered to the pro-Russian Abkhazia, Georgia cheap nike jordan shoes Army contain two infantry brigades, effectively coordinate the cheap christian louboutin direction of the Russian Bags Louis Vuitton troops in South Ossetia.

Unknown said...

new york giants jerseys
juicy couture outlet
chanel outlet
ray ban sunglasses
robert griffin jersey,joe theismann jersey,andre roberts jersey,sonny jurgensen jersey,art monk jersey,bashaud breeland jersey,barry cofield jersey,perry riley jersey,e.j. biggers jersey,duke ihenacho jersey,josh morgan jersey
mizuno shoes
seahawks jersey
stuart weitzman sale
nike free,nike free run,free running,free run,nike running
five fingers shoes
tory burch outlet online
uggs outlet
cheap oakley sunglasses
cheap jordans
mizuno running shoes
derrick rose jersey
cowboys jerseys
barcelona soccer jersey
bottega veneta wallet
nike roshe
chanel outlet,chanel handbags,chanel bags,chanel outlet,chanel 2.55
supra shoes
giants jersey
stephen curry jersey
miami dolphins jerseys
bottega veneta outlet
indianapolis colts jerseys
nike air max 2015
ray ban outlet
arizona cardinals jerseys
the north face clearance
coach outlet store
nike trainers
chelsea jersey
washington redskins jerseys
zhuweiming0627

chenlina said...

chenlina20150711
ray ban sunglasses
imitation watches
louis vuitton handbags
abercrombie store
chanel bags
chanel handbags
air max 90
soccer cleats
louis vuitton
coach outlet
michael kors uk
concords 11
chanel outlet
oakley sunglasses
gucci handbags
true religion sale
hollister clothing
cheap chanel handbags
insanity dvd
lebron 11
michael kors uk
louboutin
fendi handbags
louis vuitton handbags
louis vuitton
coach outlet store online
longchamp outlet
toms shoes
hollister
ray ban glasses
cheap jerseys wholesale
mulberry handbags
chanel outlet
louis vuitton outlet
coach outlet online
fitflop sale
michael kors outlet
ray ban outlet
louboutin
michael kors handbags

Unknown said...

2015-09-16 zhengjx
Up To 70% Off Air Retro Jordan 8s
michael kors handbags
michael kors outlet
Coach Factory Outlet Discount Online
Abercrombie And Fitch Clothing Outlet at New York
uggs outlet
Michael Kors Outlet Factory Online Store
Cheap Jordan 13 Shoes For Sale Free Shipping
ralph lauren
canada goose jackets
toms shoes
Abercrombie And Fitch New York Outlet Store
fitflops
coach outlet
coach factory outlet
Louis Vuitton Outlet Handbags Pursers In USA
Michael Kors Outlet Online Store Clearance
Coach Factory Outlet Online Sale Discount
Original Michael Kors Handbags Outlet Online
Coach Outlet Store Online Clearance
Cheap Michael Kors Handbags On Sale
Official Cheap Michael Kors Handbags Outlet
ugg boots
louis vuitton
cheap nfl jerseys
Louis Vuitton Outlet Store Locations
abercrombie & fitch
Coach Factory Outlet Official Website
louis vuitton outlet
michael kors

Unknown said...

ray ban sunglasses, http://www.raybansunglassesonline.us.com/
nike trainers, http://www.niketrainers.me.uk/
gucci handbags, http://www.guccihandbags-outlet.co.uk/
herve leger, http://www.herveleger.us.com/
timberland boots, http://www.timberlandboots.name/
coach outlet online, http://www.coachoutletonline-store.us.com/
michael kors outlet, http://www.michaelkorsoutletcanada.in.net/
juicy couture outlet, http://www.juicycoutureoutlet.net/
calvin klein underwear, http://www.calvinklein.in.net/
ray ban sunglasses, http://www.raybansunglass.us.com/
prada outlet, http://www.pradaoutlet.us/
lululemon outlet, http://www.lululemonoutletstore.in.net/
tory burch shoes, http://www.toryburchshoesoutlet.com/
michael kors outlet, http://www.michaelkorsoutlet.org.uk/
replica watches, http://www.replicawatchesforsale.us.com/
pandora jewelry, http://www.pandorajewelryoutlet.us.com/
nfl jerseys wholesale, http://www.nfljerseys-wholesale.us.com/
michael kors outlet, http://www.michaelkorsoutletonlinstore.us.com/
oakley outlet, http://www.oakleyoutlet.in.net/
oakley sunglasses, http://www.oakleysunglasses-outlet.us.com/
michael kors bags, http://www.michaelkorsbags.uk/
ray ban sunglasses, http://www.ray-bansunglasses.eu.com/
oakley sunglasses, http://www.oakley.in.net/
air max 2015, http://www.airmax2015.in.net/
the north face uk, http://www.thenorthfaces.org.uk/
swarovski outlet, http://www.swarovski-outlet.co.uk/
pandora jewelry, http://www.pandora.eu.com/
chanel handbags, http://www.chanelhandbags-outlet.co.uk/
1002maoqiuyun

Unknown said...

ray ban sunglasses, http://www.raybansunglassesonline.us.com/
nike trainers, http://www.niketrainers.me.uk/
gucci handbags, http://www.guccihandbags-outlet.co.uk/
herve leger, http://www.herveleger.us.com/
timberland boots, http://www.timberlandboots.name/
coach outlet online, http://www.coachoutletonline-store.us.com/
michael kors outlet, http://www.michaelkorsoutletcanada.in.net/
juicy couture outlet, http://www.juicycoutureoutlet.net/
calvin klein underwear, http://www.calvinklein.in.net/
ray ban sunglasses, http://www.raybansunglass.us.com/
prada outlet, http://www.pradaoutlet.us/
lululemon outlet, http://www.lululemonoutletstore.in.net/
tory burch shoes, http://www.toryburchshoesoutlet.com/
michael kors outlet, http://www.michaelkorsoutlet.org.uk/
replica watches, http://www.replicawatchesforsale.us.com/
pandora jewelry, http://www.pandorajewelryoutlet.us.com/
nfl jerseys wholesale, http://www.nfljerseys-wholesale.us.com/
michael kors outlet, http://www.michaelkorsoutletonlinstore.us.com/
oakley outlet, http://www.oakleyoutlet.in.net/
oakley sunglasses, http://www.oakleysunglasses-outlet.us.com/
michael kors bags, http://www.michaelkorsbags.uk/
ray ban sunglasses, http://www.ray-bansunglasses.eu.com/
oakley sunglasses, http://www.oakley.in.net/
air max 2015, http://www.airmax2015.in.net/
the north face uk, http://www.thenorthfaces.org.uk/
swarovski outlet, http://www.swarovski-outlet.co.uk/
pandora jewelry, http://www.pandora.eu.com/
chanel handbags, http://www.chanelhandbags-outlet.co.uk/
1002maoqiuyun

Unknown said...

ray ban sunglasses, http://www.raybansunglassesonline.us.com/
nike trainers, http://www.niketrainers.me.uk/
gucci handbags, http://www.guccihandbags-outlet.co.uk/
herve leger, http://www.herveleger.us.com/
timberland boots, http://www.timberlandboots.name/
coach outlet online, http://www.coachoutletonline-store.us.com/
michael kors outlet, http://www.michaelkorsoutletcanada.in.net/
juicy couture outlet, http://www.juicycoutureoutlet.net/
calvin klein underwear, http://www.calvinklein.in.net/
ray ban sunglasses, http://www.raybansunglass.us.com/
prada outlet, http://www.pradaoutlet.us/
lululemon outlet, http://www.lululemonoutletstore.in.net/
tory burch shoes, http://www.toryburchshoesoutlet.com/
michael kors outlet, http://www.michaelkorsoutlet.org.uk/
replica watches, http://www.replicawatchesforsale.us.com/
pandora jewelry, http://www.pandorajewelryoutlet.us.com/
nfl jerseys wholesale, http://www.nfljerseys-wholesale.us.com/
michael kors outlet, http://www.michaelkorsoutletonlinstore.us.com/
oakley outlet, http://www.oakleyoutlet.in.net/
oakley sunglasses, http://www.oakleysunglasses-outlet.us.com/
michael kors bags, http://www.michaelkorsbags.uk/
ray ban sunglasses, http://www.ray-bansunglasses.eu.com/
oakley sunglasses, http://www.oakley.in.net/
air max 2015, http://www.airmax2015.in.net/
the north face uk, http://www.thenorthfaces.org.uk/
swarovski outlet, http://www.swarovski-outlet.co.uk/
pandora jewelry, http://www.pandora.eu.com/
chanel handbags, http://www.chanelhandbags-outlet.co.uk/
1002maoqiuyun

chenlina said...

chenlina20151127
uggs boots
canada goose jackets
ugg outlet
louis vuitton handbags
gucci shoes
ray ban outlet store
mont blanc legend
michael kors handbags
ray ban sunglasses
louis vuitton handbags
cheap uggs
hollister co
kobe 9
adidas superstars
hollister
north face jackets
tory burch sale
ugg australia
louis vuitton handbags
timberland outlet
michael kors outlet online
canada goose jackets
louis vuitton outlet
hollister co,hollister jeans,hollister.com,hollister ca
coach outlet store online
michael kors outlet
louis vuitton purses
michael kors outlet
uggs on sale
adidas originals
louis vuitton
louis vuitton handbags
michael kors outlet online
giuseppe zanotti
nike roshe run women
ugg boots on sale
michaek kors outlet online
nike huarache shoes
canada goose jackets
nike trainers uk
as

oakleyses said...

air jordan pas cher, ray ban uk, nike roshe, true religion jeans, air force, abercrombie and fitch, north face, new balance pas cher, sac longchamp, longchamp pas cher, mulberry, oakley pas cher, nike free run uk, coach outlet, nike blazer, hermes, michael kors, nike air max, air max, hollister pas cher, true religion jeans, ralph lauren pas cher, vans pas cher, michael kors, coach outlet, true religion jeans, hollister, michael kors, north face, nike air max, nike roshe run, coach purses, burberry, lululemon, michael kors, lacoste pas cher, hogan, tn pas cher, sac guess, replica handbags, louboutin pas cher, vanessa bruno, timberland, kate spade handbags, converse pas cher, ralph lauren uk, nike free

oakleyses said...

moncler, moncler outlet, marc jacobs, moncler, hollister, montre pas cher, vans, ray ban, replica watches, pandora charms, louis vuitton, supra shoes, sac louis vuitton pas cher, pandora jewelry, swarovski, pandora charms, moncler, bottes ugg, barbour, canada goose, ugg,uggs,uggs canada, louis vuitton, doke gabbana outlet, converse, louis vuitton, lancel, louis vuitton, hollister, moncler, pandora jewelry, doudoune canada goose, juicy couture outlet, nike air max, converse outlet, barbour jackets, moncler, ugg,ugg australia,ugg italia, links of london, moncler, gucci, canada goose outlet, canada goose, canada goose outlet, coach outlet, canada goose uk, ugg boots uk, canada goose, juicy couture outlet, ugg pas cher, wedding dresses, canada goose

chenlina said...

chenlina20160127
soccer shoes
true religion jeans outlet
pandora outlet
abercrombie & fitch
cheap nfl jerseys
michael kors outlet
michael kors outlet online
nike free runs
canada goose outlet
kobe bryant shoes
louis vuitton outlet
ugg outlet store
gucci shoes
oakley sunglasses cheap
lebron james shoes 13
michael kors outlet online
coach factory outlet
cheap uggs
louis vuitton bags
tory burch sale
hollister clothing
chanel handbags
oakley sunglasses
air jordans
pandora jewelry
cheap jordan shoes
cheap nfl jerseys
michael kors handbags
ray ban sunglasses
uggs for women
true religion jeans
kids lebron shoes
ray ban sunglasses outlet
ugg outlet
timberland outlet
replica watches
toms shoes
kobe 9
uggs outlet
michael kors uk
as

Unknown said...

tiffany and co
louis vuitton outlet
clarisonic
true religion jeans
timberland outlet
true religion outlet
louis vuitton outlet
cheap uggs
coach outlet
true religion outlet
mlb jerseys
oakley sunglasses
adidas outlet
michael kors outlet
longchamp handbags
beats by dre
rolex watches
ray ban sunglasses
ugg boots
ugg australia
moncler uk
ray ban sunglasses
louis vuitton paris
toms shoes
louis vuitton handbags
coach factory outlet
moncler uk
gucci outlet
canada goose outlet
adidas nmd
timberland boots
juicy couture
burberry outlet
ugg boots
the north face jackets
timberland boots
new york knicks jerseys
nike outlet store
ugg sale
ugg italia
201611.5wengdongdong

raybanoutlet001 said...

cheap jordan shoes
nike roshe run
titans jersey
nike air huarache
denver broncos jerseys
michael kors handbags outlet
salvatore ferragamo
michael kors handbags
moncler jackets
michael kors handbags outlet

Unknown said...

jets jersey
san antonio spurs jerseys
ray ban sunglasses
michael kors handbags online
michael kors outlet
ralph lauren
eagles jerseys
kobe 9
jordan shoes
packers jerseys

caiyan said...

fitflops sale
cheap jordan shoes
air jordans
cubs jerseys
cheap oakley sunglasses
gucci outlet online
adidas trainers
louis vuitton handbags
coach outlet online
true religion jeans
0413shizhong

5689 said...

zzzzz2018.11.6
ugg boots clearance
canadian goose
pandora charms
ugg boots clearance
pandora outlet
pandora outlet
ralph lauren uk
mbt shoes
louboutin shoes
nike outlet