Reader small image

You're reading from  Instant Hands-on Testing with PHPUnit How-to

Product typeBook
Published inMay 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781782169581
Edition1st Edition
Languages
Right arrow
Author (1)
Michael Lively
Michael Lively
author image
Michael Lively

Michael Lively has worked in a variety of roles in the software development industry for over 15 years, from developer to development director. He has worked on a variety of different projects and a variety of different technologies over that time, from small home-grown sites serving a handful of regular users to large enterprise platforms serving millions of consumers. His current job is with Slickdeals.net, the largest and most trusted deal sharing community and a routine presence in the top 100 sites in the US. In addition to his professional work, he has been an active member of the PHP open source community. Some of his contributions include the database extension for PHPUnit and an alternative mocking framework for PHP called Phake.
Read more about Michael Lively

Right arrow

Using test fixtures (Simple)


As you begin writing tests you'll find that many of them, especially ones inside the same test case class, need to run the same code to set up the object that you are running tests against. This code is part of what is commonly called a fixture. Many test methods require the same fixture. PHPUnit allows you to support shared fixtures using the setUp() and tearDown() methods.

You have undoubtedly seen these methods implemented in some of our examples already. We will now go into further detail of how these fixtures work and what types of things you can do with them.

How to do it...

Open tests/CardTest.php and add a new setUp() method and use the $card property to hold the Card fixture.

<?php
class CardTest extends PHPUnit_Framework_TestCase
{
  private $card;
  public function setUp()
  {
    $this->card = new Card('4', 'spades');
  }
  public function testGetNumber()
  {
    $actualNumber = $this->card->getNumber();
    $this->assertEquals(4, $actualNumber, 'Number should be <4>');
  }
  public function testGetSuit()
  {
    $actualSuit = $this->card->getSuit();
    $this->assertEquals('spades', $actualSuit, 'Suit should be <spades>');
  }
  public function testIsInMatchingSet()
  {
    $matchingCard = new Card('4', 'hearts');
    $this->assertTrue($this->card->isInMatchingSet($matchingCard),
        '<4 of Spades> should match <4 of Hearts>');
  }
  public function testIsNotInMatchingSet()
  {
    $matchingCard = new Card('5', 'hearts');
    $this->assertFalse($this->card->isInMatchingSet($matchingCard),
        '<4 of Spades> should not match <5 of Hearts>');
  }
}

How it works...

You'll notice the biggest change in this method is the addition of the setUp() method. The setUp() method is run immediately before any test method in the test case. So when testGetNumber() is run, the PHPUnit framework will first execute setUp() on the same object. setUp() then initializes $this|card with a new Card object. $this|card is then used in the test to validate that the number is returned properly. Using setUp() in this way makes your tests much easier to maintain. If the signature of the Card class's constructor is changed, you will only have one place in this file to reflect that change as opposed to four separate places. You will save even more time as you add more and more tests to a single test case class.

It should also be noted that a new instance of CardTest is created each time a test method is executed. Only the code in this case is being shared. The objects that setUp() creates are not shared across tests. We will talk about how to share resources across tests shortly.

There is also a tearDown() method. It can be used to remove any resource you created inside your setUp() method. If you find yourself opening files, or sockets, or setting up other resources then you will need to use tearDown() to close those resources, delete file contents, or otherwise tear down your resources. This becomes very important to help keep your test suite from consuming too many resources. There is nothing quite like running out of inodes when you are running a large test suite!

There's more...

As we mentioned a moment ago, PHPUnit has the facility to share resources across execution of multiple tests. This is generally considered bad practice. One of the primary rules of creating tests is that tests should be independent from each other so that you can isolate and locate the code causing test failures more easily.

However, there are times when the physical resources required to create a fixture become large enough to outweigh the negatives of sharing this fixture across multiple tests. When such cases arise PHPUnit provides two methods that you can override: setUpBeforeClass() and tearDownAfterClass(). These are expected to be static methods. setUpBeforeClass() will be called prior to any tests or setUp() calls being made on a given class. tearDownAfterClass() will be called once all tests have been run and the final tearDown() call has been made. If you override these methods to create new objects or resources you would need to make sure that you set these values on static members of the test case class. Also, even if you are dealing only with objects, the tearDownAfterClass() is incredibly important to implement. If you do not implement it then any object created in setUpBeforeClass() and saved to static variables will remain in memory until all tests in your test suite have run.

Previous PageNext Page
You have been reading a chapter from
Instant Hands-on Testing with PHPUnit How-to
Published in: May 2013Publisher: PacktISBN-13: 9781782169581
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Michael Lively

Michael Lively has worked in a variety of roles in the software development industry for over 15 years, from developer to development director. He has worked on a variety of different projects and a variety of different technologies over that time, from small home-grown sites serving a handful of regular users to large enterprise platforms serving millions of consumers. His current job is with Slickdeals.net, the largest and most trusted deal sharing community and a routine presence in the top 100 sites in the US. In addition to his professional work, he has been an active member of the PHP open source community. Some of his contributions include the database extension for PHPUnit and an alternative mocking framework for PHP called Phake.
Read more about Michael Lively