Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Instant Hands-on Testing with PHPUnit How-to

You're reading from   Instant Hands-on Testing with PHPUnit How-to A practical guide to getting started with PHPUnit to improve code quality

Arrow left icon
Product type Paperback
Published in May 2013
Publisher Packt
ISBN-13 9781782169581
Length 82 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Michael Lively Michael Lively
Author Profile Icon Michael Lively
Michael Lively
Arrow right icon
View More author details
Toc

Testing traits (Intermediate)


Traits are a new concept introduced in PHP 5.4. Similar to Abstract classes they cannot be instantiated directly. You can always create a test class that uses a particular trait to test the functionality in that trait. However, PHPUnit has built-in functionality to dynamically create classes that use traits. This allows for simple testing of traits.

How to do it...

Consider a modified version of the CardCollection class that is, instead, represented as a trait.

<?php

trait CardCollectionTrait
{
  //...
  public function count()
  {
    return count($this->cards);
  }
  //...
}

You can create a test similar to what was created earlier for the CardCollection class.

<?php
class CardCollectionTraitTest extends PHPUnit_Framework_TestCase
{
  private $cardCollection;

  public function setUp()
  {
    $this->cardCollection = $this->getObjectForTrait('CardCollectionTrait');
  }

  public function testCountOnEmpty()
  {
    $this->assertEquals(0, $this->cardCollection->count());
  }
  //...
}

How it works...

Similar to how PHPUnit can be used to generate concrete implementations of abstract classes, it can also be used to generate a user of a given trait. The PHPUnit_Framework_TestCase::getObjectForTrait() method will generate and instantiate a class that uses the trait you pass as the first argument. You can then test the trait as you would test any other class.

lock icon The rest of the chapter is locked
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.
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 $19.99/month. Cancel anytime
Banner background image