PHPackages                             dotdev/api-test-case - 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. dotdev/api-test-case

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

dotdev/api-test-case
====================

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

6.0.2(5y ago)114MITPHPPHP &gt;=7.4

Since Jul 20Pushed 5y agoCompare

[ Source](https://github.com/dotdevru/ApiTestCase)[ Packagist](https://packagist.org/packages/dotdev/api-test-case)[ RSS](/packages/dotdev-api-test-case/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (3)Dependencies (17)Versions (36)Used By (0)

ApiTestCase
===========

[](#apitestcase)

[![Build Status](https://camo.githubusercontent.com/2cc97a3677a1764d3ac0804b85cd40bd3a5a679f3aa0874bf3a6f9d34713387d/68747470733a2f2f7472617669732d63692e6f72672f646f7464657672752f41706954657374436173652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/dotdevru/ApiTestCase)[![Coverage Status](https://camo.githubusercontent.com/f3cfb82944b0ce514288dabf8a560869b760847e7bff3da2c489143a988e345b/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f646f7464657672752f41706954657374436173652f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/dotdevru/ApiTestCase?branch=master)

**ApiTestCase** is a PHPUnit TestCase that will make your life as a Symfony API developer much easier. It extends basic [Symfony](https://symfony.com/) WebTestCase with some cool features.

Thanks to [PHP-Matcher](https://github.com/coduo/php-matcher) you can, according to its readme, "write expected json responses like a gangster". We definitely agree.

It also uses [Alice](https://github.com/nelmio/alice) for easy Doctrine fixtures loading.

Features:

- Clear TDD workflow for API development with Symfony;
- JSON/XML matching with clear error messages;
- Fixtures loading with Alice *(optional)*;

Installation
------------

[](#installation)

Assuming you already have Composer installed globally:

```
$ composer require --dev lchrusciel/api-test-case
```

And it's done! ApiTestCase is working with the default configuration.

Usage
-----

[](#usage)

We provide two base classes for your test cases: JsonApiTestCase and the XmlApiTestCase. Choose one based on the format of the API you want to create.

### Json Example

[](#json-example)

The basic TDD workflow is the following:

1. Write a test case that sends the request and use `assertResponse` assertion method to check if response contents are matching your expectations. You need a name for the response file;
2. Create the file with name that you picked in step 1. and put expected response contents there. It should be put in `src/AppBundle/Tests/Responses/Expected/hello_world.json` for example.
3. Make it red.
4. Make it green.
5. Refactor.

Let's see a simple example! Write the following test:

```
namespace AppBundle\Tests\Controller\HelloWorldTest;

use ApiTestCase\JsonApiTestCase;

class HelloWorldTest extends JsonApiTestCase
{
    public function testGetHelloWorldResponse()
    {
        $this->client->request('GET', '/');

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'hello_world');
    }
}
```

Now define the expected response file:

```
{
    "message": "Hello ApiTestCase World!"
}
```

Run your tests:

```
$ bin/phpunit
```

Your test should fail with some errors, you are probably missing the controller and routing, so go ahead and define them! As soon as you implement your Controller and configure appropriate routing, you can run your tests again:

If the response contents will match our expectations, console will present a simple message:

```
OK (1 tests, 2 assertions)
```

Otherwise it will present diff of received messages:

```
"Hello ApiTestCase World" does not match "Hello ApiTestCase World!".
@@ -1,4 +1,3 @@
 {
-    "message": "Hello ApiTestCase World!"
+    "message": "Hello ApiTestCase World"
 }
-
```

Firstly, function `assertResponse` will check the response code (200 is a default response code), then it will check if header of response contains `application/json` content type. At the end it will check if the response contents matches the expectation. Sometimes you can't predict some values in the response, for example autogenerated date or id from the database. No magic is needed here because [PHP-Matcher](https://github.com/coduo/php-matcher) comes with a helping hand. These are just a few examples of available patterns:

- `@string@`
- `@integer@`
- `@boolean@`
- `@array@`

Check for more on [PHP-Matcher's documentation](https://github.com/coduo/php-matcher).

With these patterns your expected response will look like this:

```
{
    "message": "@string@"
}
```

With this in place, any string under key `message` will match the pattern. More complicated expected response could look like this:

```
[
    {
        "id": "@integer@",
        "name": "Star-Wars T-shirt",
        "sku": "SWTS",
        "price": 5500,
        "sizes": "@array@",
        "created_at": "@string@.isDateTime()"
    },
    {
        "id": "@integer@",
        "name": "Han Solo Mug",
        "sku": "HSM",
        "price": 500,
        "sizes": "@array@",
        "created_at": "@string@.isDateTime()"
    }
]
```

And will match the following list of products:

```
array(
    array(
        'id' => 1,
        'name' => 'Star-Wars T-shirt',
        'sku' => 'SWTS',
        'price' => 5500,
        'sizes' => array('S', 'M', 'L'),
        'created_at' => new \DateTime(),
    ),
    array(
        'id' => 2,
        'name' => 'Han Solo Mug',
        'sku' => 'HSM',
        'price' => 500,
        'sizes' => array('S', 'L'),
        'created_at' => new \DateTime(),
    ),
)
```

### Testing With Database Fixtures

[](#testing-with-database-fixtures)

ApiTestCase is integrated with `nelmio/alice`. Thanks to this nice library you can easily load your fixtures when you need them. You have to define your fixtures and place them in an appropriate directory. Here is some example how to define your fixtures and use case. For more information how to define your fixtures check [Alice's documentation](https://github.com/nelmio/alice).

In order to use Alice with Doctrine, you should enable two additional bundles:

**Symfony 4.0+**

```
// config/bundles.php
return [
    // ...

    Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle::class => ['test' => true],
    Fidry\AliceDataFixtures\Bridge\Symfony\FidryAliceDataFixturesBundle::class => ['test' => true],
];
```

**Symfony 3**

```
// app/AppKernel.php
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        // ...

        if ('test' === $this->getEnvironment()) {
            new Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle(),
            new Fidry\AliceDataFixtures\Bridge\Symfony\FidryAliceDataFixturesBundle(),
        }
    }
}
```

Now, let's say you have a mapped Doctrine entity called Book in your application:

```
    class Book
    {
        private $id;
        private $title;
        private $author;

        // ...
    }
```

To load fixtures for the test, you need to define a simple `YAML` file in `src/AppBundle/Tests/DataFixtures/ORM/books.yml`:

```
    ApiTestCase\Test\Entity\Book:
        book1:
            title: "Lord of The Rings"
            author: "J. R. R. Tolkien"
        book2:
            title: "Game of Thrones"
            price: "George R. R. Martin"
```

Finally, to use these fixtures in a test, just call a proper method:

```
    public function testBooksIndexAction()
    {
        // This method require subpath to locate specific fixture file in your DataFixtures/ORM directory.
        $this->loadFixturesFromFile('books.yml');

        // There is another method that allows you to load fixtures from directory.
        $this->loadFixturesFromDirectory('big_library');
    }
```

Configuration Reference
-----------------------

[](#configuration-reference)

To customize your test suite configuration you can add a few more options to phpunit.xml:

```

```

- `KERNEL_CLASS` allows you to specify exactly which class should be used in order to setup the Kernel.
- `ERESPONSE_DIR` variable contain paths to folder with expected responses. It is used when API result is compared with existing json file. If this value isn't set, ApiTestCase will try to guess location of responses, looking for the responses in a folder: '../Responses' relatively located to your controller test class.
- `FIXTURES_DIR` variable contains a path to folder with your data fixtures. By default if this variable isn't set it will search for `../DataFixtures/ORM/` relatively located to your test class . ApiTestCase throws RunTimeException if folder doesn't exist or there won't be any files to load.
- `OPEN_ERROR_IN_BROWSER` is a flag which turns on displaying error in a browser window. The default value is false.
- `OPEN_BROWSER_COMMAND` is a command which will be used to open browser with an exception.
- `IS_DOCTRINE_ORM_SUPPORTED` is a flag which turns on doctrine support includes handy data fixtures loader and database purger.
- `TMP_DIR` variable contains a path to temporary folder, where the log files will be stored.
- `ESCAPE_JSON` is a flag which turns on escaping (unicode characters and slashes) of your JSON output before comparing it to expected data. The default value is false. This flag only exists for backwards compatibility with previous versions of ApiTestCase (when turned on) and will be removed in a future version.

Sample Project
--------------

[](#sample-project)

In the `test/` directory, you can find sample Symfony project with minimal configuration required to use this library.

### Testing

[](#testing)

In order to run our PHPUnit tests suite, execute following commands:

```
$ composer install
$ test/app/console doctrine:database:create
$ test/app/console doctrine:schema:create
$ bin/phpunit
```

Bug Tracking and Suggestions
----------------------------

[](#bug-tracking-and-suggestions)

If you have found a bug or have a great idea for improvement, please [open an issue on this repository](https://github.com/lchrusciel/ApiTestCase/issues/new).

Versioning
----------

[](#versioning)

Releases will be numbered with the format `major.minor.patch`.

And constructed with the following guidelines.

- Breaking backwards compatibility bumps the major.
- New additions without breaking backwards compatibility bumps the minor.
- Bug fixes and misc changes bump the patch.

For more information on SemVer, please visit [semver.org website](http://semver.org/).

MIT License
-----------

[](#mit-license)

License can be found [here](https://github.com/lchrusciel/ApiTestCase/blob/master/LICENSE).

Authors
-------

[](#authors)

The library was originally created by:

- [Łukasz Chruściel](https://github.com/lchrusciel)
- [Michał Marcinkowski](https://github.com/michalmarcinkowski)
- [Paweł Jędrzejewski](https://github.com/pjedrzejewski)
- [Arkadiusz Krakowiak](https://github.com/Arminek)

at [Lakion](http://github.com/Lakion/) company under  repository.

See the list of [contributors](https://github.com/lchrusciel/ApiTestCase/graphs/contributors).

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~54 days

Total

30

Last Release

2012d ago

Major Versions

v1.2.0 → v2.0.02017-06-27

v2.0.0 → v3.0.0-RC.12017-12-20

v3.1.4 → v4.0.02019-02-05

4.1.x-dev → v5.0.0-alpha2019-07-27

v5.0.0 → 6.0.02020-10-24

PHP version history (6 changes)1.0.0-alpha.1PHP ^5.5.9|^7.0

1.0.0-alpha.2PHP ^5.6|^7.0

v2.0.0PHP ^7.0

v3.0.0-RC.2PHP ^7.1

v5.0.0-alphaPHP ^7.2

6.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/8f492002be1ed8b7574510e3c195b446c0ae99fcb91f652693862ccb2d8183d8?d=identicon)[dotdev](/maintainers/dotdev)

---

Top Contributors

[![lchrusciel](https://avatars.githubusercontent.com/u/6213903?v=4)](https://github.com/lchrusciel "lchrusciel (143 commits)")[![pamil](https://avatars.githubusercontent.com/u/1897953?v=4)](https://github.com/pamil "pamil (33 commits)")[![angelov](https://avatars.githubusercontent.com/u/138429?v=4)](https://github.com/angelov "angelov (20 commits)")[![ashceo](https://avatars.githubusercontent.com/u/49865434?v=4)](https://github.com/ashceo "ashceo (18 commits)")[![michalmarcinkowski](https://avatars.githubusercontent.com/u/7572437?v=4)](https://github.com/michalmarcinkowski "michalmarcinkowski (12 commits)")[![Arminek](https://avatars.githubusercontent.com/u/6368946?v=4)](https://github.com/Arminek "Arminek (10 commits)")[![loic425](https://avatars.githubusercontent.com/u/8329789?v=4)](https://github.com/loic425 "loic425 (9 commits)")[![bendavies](https://avatars.githubusercontent.com/u/625392?v=4)](https://github.com/bendavies "bendavies (8 commits)")[![Zales0123](https://avatars.githubusercontent.com/u/6212718?v=4)](https://github.com/Zales0123 "Zales0123 (7 commits)")[![pjedrzejewski](https://avatars.githubusercontent.com/u/614970?v=4)](https://github.com/pjedrzejewski "pjedrzejewski (7 commits)")[![mamazu](https://avatars.githubusercontent.com/u/14860264?v=4)](https://github.com/mamazu "mamazu (3 commits)")[![emodric](https://avatars.githubusercontent.com/u/362286?v=4)](https://github.com/emodric "emodric (3 commits)")[![stloyd](https://avatars.githubusercontent.com/u/67402?v=4)](https://github.com/stloyd "stloyd (2 commits)")[![LaetitiaRiffaud](https://avatars.githubusercontent.com/u/11833909?v=4)](https://github.com/LaetitiaRiffaud "LaetitiaRiffaud (2 commits)")[![vntw](https://avatars.githubusercontent.com/u/502368?v=4)](https://github.com/vntw "vntw (2 commits)")[![MichaelKubovic](https://avatars.githubusercontent.com/u/1603975?v=4)](https://github.com/MichaelKubovic "MichaelKubovic (2 commits)")[![rodnaph](https://avatars.githubusercontent.com/u/447579?v=4)](https://github.com/rodnaph "rodnaph (1 commits)")[![Shine-neko](https://avatars.githubusercontent.com/u/884441?v=4)](https://github.com/Shine-neko "Shine-neko (1 commits)")[![videni](https://avatars.githubusercontent.com/u/4058341?v=4)](https://github.com/videni "videni (1 commits)")[![alcaeus](https://avatars.githubusercontent.com/u/383198?v=4)](https://github.com/alcaeus "alcaeus (1 commits)")

---

Tags

jsonphpunitapisymfonyxmlTDDdoctrine

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/dotdev-api-test-case/health.svg)

```
[![Health](https://phpackages.com/badges/dotdev-api-test-case/health.svg)](https://phpackages.com/packages/dotdev-api-test-case)
```

###  Alternatives

[lchrusciel/api-test-case

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

4115.5M63](/packages/lchrusciel-api-test-case)[hautelook/alice-bundle

Symfony bundle to manage fixtures with Alice and Faker.

19519.4M34](/packages/hautelook-alice-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopsys/http-smoke-testing

HTTP smoke test case for testing all configured routes in your Symfony project

68258.7k1](/packages/shopsys-http-smoke-testing)

PHPackages © 2026

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