PHPackages                             lastzero/test-tools - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. lastzero/test-tools

ActiveLibrary[Testing &amp; Quality](/categories/testing)

lastzero/test-tools
===================

Increases testing productivity by adding a service container and self-initializing fakes to PHPUnit

v5.0.1(3y ago)2244.3k↓37.9%613MITPHPPHP &gt;=7.2

Since Oct 21Pushed 3y ago3 watchersCompare

[ Source](https://github.com/lastzero/test-tools)[ Packagist](https://packagist.org/packages/lastzero/test-tools)[ Docs](https://github.com/lastzero/test-tools)[ RSS](/packages/lastzero-test-tools/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (11)Versions (45)Used By (13)

TestTools for PHPUnit
=====================

[](#testtools-for-phpunit)

[![License](https://camo.githubusercontent.com/0a3d33f699f15ec34846f50c4a40dbcb4c8576f3f886bdd034236305acf47cf8/68747470733a2f2f706f7365722e707567782e6f72672f6c6173747a65726f2f746573742d746f6f6c732f6c6963656e73652e737667)](https://packagist.org/packages/lastzero/test-tools)[![Latest Stable Version](https://camo.githubusercontent.com/c96fd20f3b8ddc77883109ee84feac1cffd01cad541d931eb89b657344a360b3/68747470733a2f2f706f7365722e707567782e6f72672f6c6173747a65726f2f746573742d746f6f6c732f762f737461626c652e737667)](https://packagist.org/packages/lastzero/test-tools)[![Total Downloads](https://camo.githubusercontent.com/c71c9b512e1ee7365a09a1f24b1e68f60ef83a4b0c548d3490cf2c2fca740c9d/68747470733a2f2f706f7365722e707567782e6f72672f6c6173747a65726f2f746573742d746f6f6c732f646f776e6c6f6164732e737667)](https://packagist.org/packages/lastzero/test-tools)[![Test Coverage](https://camo.githubusercontent.com/460e66681f8a978c5c3575222b9b26db0fae774594c7aa16d99b1b036c41fb70/68747470733a2f2f636f6465636f762e696f2f67682f6c6173747a65726f2f746573742d746f6f6c732f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/lastzero/test-tools)[![Build Status](https://camo.githubusercontent.com/f7f7425b56e64777e4bdc9dc26749f449cbcd99dde943f931b42caa052eb435f/68747470733a2f2f7472617669732d63692e6f72672f6c6173747a65726f2f746573742d746f6f6c732e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/lastzero/test-tools)

**This library improves testing productivity by adding a configurable service container and self-initializing fakes to PHPUnit.**

- **UnitTestCase** adds the Symfony [service container](http://symfony.com/doc/current/service_container.html) to `PHPUnit\Framework\TestCase` (configuration via `config.yml` file in the Tests directory)
- **WebTestCase** and **CommandTestCase** extend UnitTestCase for functional testing of Symfony Web and CLI applications
- **FileFixture** reads and writes serialized data from/to the file system
- **SelfInitializingFixtureTrait** and **BlackBox** add fixture support to almost any database or service client (record and playback) to provide self-initializing fakes as test doubles
- **Doctrine DBAL** is supported out of the box

Service Container
-----------------

[](#service-container)

Here’s an example of a test case built with `TestTools\TestCase\UnitTestCase` – note the **setUp()** method, which get’s the ready-to-use object from the dependency injection container:

```
use TestTools\TestCase\UnitTestCase;

class FooTest extends UnitTestCase
{
    protected $foo;

    public function setUp()
    {
        $this->foo = $this->get('foo');
    }

    public function testBar()
    {
        $result = $this->foo->bar('Pi', 2);
        $this->assertEquals(3.14, $result);
    }
}
```

To define services, simply create a `config.yml` (optionally `config.local.yml` for local modifications) in your base test directory, for example

```
Bundle/Example/Tests/config.yml

```

The YAML file must contain the sections "parameters" and "services". If you're not yet familiar with dependency injection or the config file format, please read the documentation on symfony.com (it's really simple):

[http://symfony.com/doc/current/components/dependency\_injection/introduction.html](http://symfony.com/doc/current/components/dependency_injection/introduction.html)

The Symfony service container was chosen, because of it's easy to understand container configuration in YAML.

Since global state must be avoided while performing tests, the service instances are not cached between tests. The service definitions in the container are reused however. This significantly improves test performance compared to a full container reinitialization before each test (about 5 to 10 times faster).

TestTools can be used to test any application, framework or library, just like `PHPUnit\Framework\TestCase`.

Classic vs Mockist Style of Unit Testing
----------------------------------------

[](#classic-vs-mockist-style-of-unit-testing)

These tools **simplify writing unit tests using real objects and test doubles** via dependency injection, so some developers might be concerned that the resulting tests are not *true* unit tests as **class dependencies are not mocked by default**. Mocking is creating objects that simulate the behaviour of real objects. These apparently conflicting approaches are referred to as the **classic and mockist styles of unit testing**:

"The **classical TDD style** is to use **real objects** if possible and a double if it's awkward to use the real thing. So a classical TDDer would use a real warehouse and a double for the mail service. The kind of double doesn't really matter that much.

A **mockist TDD** practitioner, however, will always use a mock for any object with interesting behavior. In this case for both the warehouse and the mail service." -- [Martin Fowler](http://martinfowler.com/articles/mocksArentStubs.html)

[Mocks and test doubles](http://martinfowler.com/bliki/TestDouble.html) are required to be able to test sometimes, but creating and maintaining mocks can be a boring, time-consuming endeavour. Therefore, you should think about avoiding their widespread usage and prefer using real objects instead. From my experience, they do no harm – quite the contrary: You can instantly see, how the real objects interact with each other instead of waiting for functional tests. Actually, the need for excessive mocking is an indicator for bad software design.

In theory, the mockist style can be a bit **more precise** when it comes to finding a broken line of code, because all classes are tested in complete isolation. In practice, **classic unit tests will also provide you with a stack trace** that points you to the right line of code:

"We didn't find it difficult to track down the actual fault, even if it caused neighboring tests to fail. **So we felt isolation wasn't an issue in practice**." -- [Martin Fowler](http://martinfowler.com/bliki/UnitTest.html)

In the worst case, more than one test case fails, if just one class or function is broken – this will give you even more information about the issue and allows to find and fix affected code easily.

Even code that depends on databases or Web services, can be easily tested using **self-initializing fixtures** instead of hand-written mocks. The only thing they can not properly simulate is state, but robust unit tests shouldn't depend on state anyways. If you want to test state, use [functional tests of the user interface or API](http://martinfowler.com/bliki/TestPyramid.html) instead.

Self-initializing Fakes
-----------------------

[](#self-initializing-fakes)

The concept of [self-initializing fakes](http://martinfowler.com/bliki/SelfInitializingFake.html) as test doubles can be applied to all types of external data stores (databases) and services like SOAP or REST APIs.

`SelfInitializingFixtureTrait` enables existing classes to work with file based fixtures (record and playback):

```
use TestTools\Fixture\SelfInitializingFixtureTrait;

class Foo extends SomeBaseClass
{
    use SelfInitializingFixtureTrait;

    public function bar($name, $type, array $baz = array())
    {
        return $this->callWithFixtures('bar', func_get_args());
    }
}
```

The Doctrine connection class (`TestTools\Doctrine\DBAL\Connection`) serves as a ready-to-use example. It works as a wrapper for the standard connection class (white box inheritance). Black box inheritance (`TestTools\Fixture\BlackBox`) can be used to encapsulate any client interface.

`TestTools\TestCase\WebTestCase.php` can be used for functional testing of Symfony controllers based on the regular service configuration of your application:

```
use TestTools\TestCase\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;

class FooControllerTest extends WebTestCase
{
    protected function configureFixtures(ContainerInterface $container)
    {
        // Service instance must provide a useFixtures() method for this to work
        $container->get('db')->useFixtures($this->getFixturePath());
    }

    public function testGetBar()
    {
        $response = $this->getRequest('/foo/bar/Pi', array('precision' => 2));
        $this->assertEquals(3.14, $response->getContent());
    }
}
```

Service container configuration for self-initializing fakes
-----------------------------------------------------------

[](#service-container-configuration-for-self-initializing-fakes)

A config parameter "fixture.path" (for storing file based fixtures as fakes) is automatically set based on the test class filename and path to avoid conflicts/dependencies between different tests and enforce a consistent naming scheme. The directory is created automatically. The parameter "base.path" is also available (points to the parent directory of "Tests").

Example container configuration (`TestTools/Tests/config.yml`):

```
parameters:
    dbal.params:
        driver:         mysqli
        host:           localhost
        port:           3306
        dbname:         testtools
        charset:        utf8
        user:           testtools
        password:       testtools

services:
    dbal.driver:
        class: Doctrine\DBAL\Driver\Mysqli\Driver

    dbal.connection:
        class: TestTools\Doctrine\DBAL\Connection
        arguments:
            - %dbal.params%
            - "@dbal.driver"
        calls:
            - [setFixturePrefix, ['sql']]
            - [useFixtures, ["%fixture.path%"]]
```

When using a service container in conjunction with fixtures, you don't need to care about different environments such as development and production: Configuration details (e.g. login credentials) must be valid for development environments only, since service / database requests should be replaced by fixtures from the file system after the corresponding tests were running for the first time. If a test fails on Jenkins or Travis CI because of invalid URLs or credentials in config.yml, you must make sure that all code that accesses external resources is using fixtures (or mock objects) and that all fixtures are checked in properly.

Composer
--------

[](#composer)

If you are using composer, simply run:

```
composer require --dev lastzero/test-tools
```

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 99.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~73 days

Recently: every ~437 days

Total

44

Last Release

1414d ago

Major Versions

v0.9 → v1.0.02014-10-07

v1.2.0 → v2.0.02015-12-01

v2.1.0 → v3.0.02017-02-04

v3.0.2 → v4.0.02017-08-15

v4.2.1 → v5.0.02019-02-06

PHP version history (6 changes)v0.1PHP &gt;=5.4

v2.0.0PHP &gt;=5.5.9

v2.1.0PHP &gt;=7.0.0

v3.0.1PHP &gt;=7.0

v5.0.0PHP ^7.2

v5.0.1PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/f932b09a688c990f2869e72c771bf0eeb009b264a47a1cf78d54c13f566511da?d=identicon)[lastzero](/maintainers/lastzero)

---

Top Contributors

[![lastzero](https://avatars.githubusercontent.com/u/301686?v=4)](https://github.com/lastzero "lastzero (186 commits)")[![m0ppers](https://avatars.githubusercontent.com/u/819421?v=4)](https://github.com/m0ppers "m0ppers (1 commits)")

---

Tags

dependency-injectionfixturesinitializing-fixturesmocksphpphpunitsymfonytest-driven-developmenttesttoolsunittestcasetestingphpunitsymfonyFixturedependency-injectionmocktest doubledoctrinedbal

### Embed Badge

![Health badge](/badges/lastzero-test-tools/health.svg)

```
[![Health](https://phpackages.com/badges/lastzero-test-tools/health.svg)](https://phpackages.com/packages/lastzero-test-tools)
```

###  Alternatives

[behat/behat

Scenario-oriented BDD framework for PHP

4.0k96.8M2.0k](/packages/behat-behat)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[php-mock/php-mock-phpunit

Mock built-in PHP functions (e.g. time()) with PHPUnit. This package relies on PHP's namespace fallback policy. No further extension is needed.

1718.2M399](/packages/php-mock-php-mock-phpunit)[matthiasnoback/symfony-dependency-injection-test

Library for testing user classes related to the Symfony Dependency Injection Component

2439.0M887](/packages/matthiasnoback-symfony-dependency-injection-test)[matthiasnoback/symfony-config-test

Library for testing user classes related to the Symfony Config Component

1679.8M395](/packages/matthiasnoback-symfony-config-test)[lchrusciel/api-test-case

Perfect PHPUnit TestCase for JSON/XML API TDD with Symfony.

4115.5M63](/packages/lchrusciel-api-test-case)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
