PHPackages                             nivseb/php-mock-server-connector - 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. nivseb/php-mock-server-connector

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

nivseb/php-mock-server-connector
================================

Small tool to use mock-server/mockserver in a easy way from php based tests.

v2.1.0(7mo ago)33.4k↓42.3%1[4 issues](https://github.com/nivseb/php-mock-server-connector/issues)[2 PRs](https://github.com/nivseb/php-mock-server-connector/pulls)MITPHPPHP ^8.2CI passing

Since Oct 18Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/nivseb/php-mock-server-connector)[ Packagist](https://packagist.org/packages/nivseb/php-mock-server-connector)[ Docs](https://github.com/nivseb/php-mock-server-connector)[ RSS](/packages/nivseb-php-mock-server-connector/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (8)Versions (13)Used By (0)

PHP Mock Server Connector
=========================

[](#php-mock-server-connector)

[![Tests](https://camo.githubusercontent.com/02d5cdb4d38b0596098ba03678213cfe7a545ac85ed6f65b9340a6eedf9a8ef7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6e69767365622f7068702d6d6f636b2d7365727665722d636f6e6e6563746f722f746573742e796d6c3f6272616e63683d6d61696e266c6162656c3d5465737473)](https://github.com/nivseb/php-mock-server-connector/actions/workflows/tests.yml)[![Supported PHP Version](https://camo.githubusercontent.com/2260d64b54132787b8f45bb0d7499edb74a5dbca46f341d073ff8a398134ae77/68747470733a2f2f62616467656e2e6e65742f7061636b61676973742f7068702f6e69767365622f7068702d6d6f636b2d7365727665722d636f6e6e6563746f723f636f6c6f723d383839326266)](https://www.php.net/supported-versions)[![Latest Stable Version](https://camo.githubusercontent.com/4461970b4fb6df0377841fea036a4a837f0dd3094f5b83e12cd041ff7521cc44/68747470733a2f2f706f7365722e707567782e6f72672f6e69767365622f7068702d6d6f636b2d7365727665722d636f6e6e6563746f722f762f737461626c652e737667)](https://packagist.org/packages/nivseb/php-mock-server-connector)[![Total Downloads](https://camo.githubusercontent.com/d01403bb892f2c3d096eea22589e18be77680d6ab6dd250ca06a801044973e9c/68747470733a2f2f706f7365722e707567782e6f72672f6e69767365622f7068702d6d6f636b2d7365727665722d636f6e6e6563746f722f646f776e6c6f6164732e737667)](https://packagist.org/packages/nivseb/php-mock-server-connector)

PHP Mock Server Connector is a tool that make it easy to use the [MockServer](https://www.mock-server.com) in php based tests. The method of utilisation is based on the [Mockery](https://github.com/mockery/mockery) project. The creation of Expectations is therefore very similar.

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

[](#installation)

1. To install PHP Mock Server Connector you can easily use composer.

    ```
    composer require --dev nivseb/php-mock-server-connector
    ```
2. You need a running instance of the [MockServer](https://www.mock-server.com/mock_server/getting_started.html#start_mockserver).
3. Existing test setup for php based test. For example a setup with [PHPUnit](https://phpunit.de).

Usage
-----

[](#usage)

### Setup in your tests

[](#setup-in-your-tests)

After the installation, you can start to use the connector in your tests. The first step is now to connect to the [MockServer instance](https://www.mock-server.com), for that add the following code to your test. This can be done in a single test case or in another setup part for your tests (like the setUp Method in PHPUnit tests). But this need the first step that is executed.

```
    use Nivseb\PhpMockServerConnector\Server;
    MockServer::init('https://your_mock_server.localhost');
```

The next part you must add is this code. It must be placed after your tests, for example in the `tearDown` method in PHPUnit tests. This code will verify the expectations in your [MockServer instance](https://www.mock-server.com).

```
    use Nivseb\PhpMockServerConnector\Server;
    MockServer::close();
```

For PHPUnit tests the package comes with the trait `UseMockServer`. This adds two methods to the test class `initMockServer` and `closeMockServer`. The method `closeMockServer` is called in the tearDown from the phpunit test. Now your integration can look like this:

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use PHPUnit\Framework\TestCase;

    class YourTest extends TestCase {
        use UseMockServer;

        protected function setUp(): void
        {
            parent::setUp();
            $this->initMockServer('https://your_mock_server.localhost');
        }
    }
```

### Create expectation

[](#create-expectation)

After you finished the setup for your test cases, you can now add expectations to you tests. First you must create an instance for an endpoint. This endpoint is the route entry point for a mock. This design allow you that you can build mocks for different other external apis with only one [MockServer instance](https://www.mock-server.com).

```
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;

    $mockServer = new MockServerEndpoint('/rootPath');
```

For every request that you want to mock you call now the allows method. That give you a `PendingExpectation`, this will create the expectation at your [MockServer instance](https://www.mock-server.com) on destruct or with the call of the `run` method.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/rootPath');

    $mockServer->allows('GET', '/firstPath')->andReturn(200, ['data' => 'This is a JSON test content.']);
    // OR
    $myRequest = $mockServer->allows('GET', '/secondPath');
    $myRequest->andReturn(200, ['data' => 'This is a JSON test content.']);
    $myRequest->run();
```

The expectation will be verified on the close call for the mock server, see for that [Setup in your tests](#setup-in-your-tests).

Supported request expectations
------------------------------

[](#supported-request-expectations)

### methods and uri

[](#methods-and-uri)

You can create expectations for methods and paths in all combinations that are possible with the [MockServer](https://www.mock-server.com).

#### Parameters

[](#parameters)

To add a check for parameters to your expectations, you can call the method `withPathParameters` or `withQueryParameters`.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    // Expected: /test/myExpectedPath?myQueryParameter=myExpectedValue
    $mockServer = new MockServerEndpoint('/test');
    $mockServer
        ->allows('GET', '/{myPathParameter}')
        ->withPathParameters(['myPathParameter' => 'myExpectedPath'])
        ->withQueryParameters(['myQueryParameter' => 'myExpectedValue']);
```

### Request Headers

[](#request-headers)

You can add expected headers in the request by calling the withHeaders method on the pending expectation.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/test');
    $mockServer->allows('GET', '/')->withHeaders(['myHeader' => 'myExpectedValue']);
```

### Body

[](#body)

A request body can be expected with a call of the `withBody` method. The Body can be sent as array or string.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/test');
    $mockServer->allows('POST', '/')->withBody(['data' => 'This is a JSON test content.']);
```

### Multiple calls

[](#multiple-calls)

With the `times` method you can define that a request should be executed multiple times.

Response
--------

[](#response)

The response for an expectation can be defined in with the `andReturn` method. For the response you can define the status code, body and headers.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/test');
    $mockServer->allows('GET', '/')->andReturn(200, ['data' => 'This is a JSON test content.']);
```

Defaults
--------

[](#defaults)

Every expectation comes with some default values. This example will define, that the request is executed one time and return an empty response with the status code 200.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/');
    $mockServer->allows('GET', '/');
```

Advance
-------

[](#advance)

### Naming Expectations

[](#naming-expectations)

If you have to add many expectations in the same test szenario, it can be difficult to differentiate between that expectations. For that case it is possible to give each expectation a custom name. By default, the name is build from method and path.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/');
    $mockServer->allows('GET', '/records/1')->andReturn(200);  // result to name `GET /records/1`
    $mockServer->allows('GET', '/records/2')->name('Load Record 2')->andReturn(200); // result to name `Load Record 2`
    $mockServer->allows('GET', '/records/3')->name('Load Record 3')->andReturn(200); // result to name `Load Record 3`
```

### Duplicate Expectation

[](#duplicate-expectation)

In some cases you expect nearly same request twice, but only with a little change in the response or request. In that case, you can build a new expectation from an existing and add your changes to the new one. this example shows a definition that expect 2 requests and answer the first one with a 200 response and the second call to with a 304 response.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    $mockServer = new MockServerEndpoint('/');
    $firstExpectation = $mockServer->allows('GET', '/')->once()->andReturn(200);
    $mockServer->duplicate($firstExpectation)->andReturn(304);
```

Example
-------

[](#example)

Here you have an example for a full functional PHPUnit test case.

```
    use Nivseb\PhpMockServerConnector\PhpUnit\UseMockServer;
    use Nivseb\PhpMockServerConnector\PhpUnit\MockServerEndpoint;
    use PHPUnit\Framework\TestCase;
    use GuzzleHttp\Client;

    class ExampleTest extends TestCase {
        use UseMockServer;

        protected function setUp(): void
        {
            parent::setUp();
            $this->initMockServer('https://your_mock_server.localhost');
        }

        public function testMyRequest() : void {
            $mockServer = new MockServerEndpoint('/rootPath');
            $mockServer->allows('GET', '/mySubPath')->andReturn(200, ['data' => 'This is a JSON test content.'])

            $client = new Client(['base_uri' => 'https://your_mock_server.localhost/rootPath'])
            $response = $this->client->get('/mySubPath');

            self::assertEquals(200, $response->getStatusCode());
            self::assertEquals('{"data":"This is a JSON test content."}',$response->getBody()->getContents());
        }
    }
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance43

Moderate activity, may be stable

Popularity26

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 86.4% 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 ~56 days

Recently: every ~77 days

Total

7

Last Release

239d ago

Major Versions

v1.2.0 → v2.0.02025-08-26

PHP version history (3 changes)v1.0.0PHP &gt;=8.1

v1.2.0PHP ^8.1

v2.0.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/5ab68ab2a78069db3160d3194e98b244061024f5cd65389a28e28ecfd430b4c7?d=identicon)[nivseb](/maintainers/nivseb)

---

Top Contributors

[![nivseb](https://avatars.githubusercontent.com/u/1013829?v=4)](https://github.com/nivseb "nivseb (51 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (7 commits)")[![charjr](https://avatars.githubusercontent.com/u/102669158?v=4)](https://github.com/charjr "charjr (1 commits)")

---

Tags

httpmockphptestingrequestphptestingphpunitmockingtestmock

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nivseb-php-mock-server-connector/health.svg)

```
[![Health](https://phpackages.com/badges/nivseb-php-mock-server-connector/health.svg)](https://phpackages.com/packages/nivseb-php-mock-server-connector)
```

###  Alternatives

[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)[blastcloud/guzzler

Supercharge your app or SDK with a testing library specifically for Guzzle.

272419.3k35](/packages/blastcloud-guzzler)[quizlet/hammock

Hammock is a stand-alone mocking library for Hacklang.

27445.5k](/packages/quizlet-hammock)[elliotchance/concise

Concise is test framework for using plain English and minimal code, built on PHPUnit.

45223.8k4](/packages/elliotchance-concise)[janmarek/mockista

Mockista is library for mocking, which I've written, because I find mocking in PHPUnit awful.

29221.0k28](/packages/janmarek-mockista)

PHPackages © 2026

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