Giter Site home page Giter Site logo

php-mock-server-connector's Introduction

PHP Mock Server Connector

Tests Supported PHP Version Latest Stable Version Total Downloads

PHP Mock Server Connector is a tool that make it easy to use the MockServer in php based tests. The method of utilisation is based on the Mockery project. The creation of Expectations is therefore very similar.

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.
  3. Existing test setup for php based test. For example a setup with PHPUnit.

Usage

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, 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.

    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

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.

    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 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.

Supported request expectations

methods and uri

You can create expectations for methods and paths in all combinations that are possible with the MockServer.

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

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

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('GET', '/')->withBody(['data' => 'This is a JSON test content.']);

Multiple calls

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

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

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', '/');

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());
        }
    }

php-mock-server-connector's People

Contributors

nivseb avatar

Stargazers

Arne Ziegert avatar  avatar Florian Evertz avatar

Watchers

Lucian avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.