All Projects → donatj → Mock Webserver

donatj / Mock Webserver

Licence: mit
Simple mock web server in PHP for unit testing.

Projects that are alternatives of or similar to Mock Webserver

phake
PHP Mocking Framework
Stars: ✭ 464 (+465.85%)
Mutual labels:  mock, phpunit
Php Mock Phpunit
Mock built-in PHP functions (e.g. time() or rand()) in PHPUnit.
Stars: ✭ 121 (+47.56%)
Mutual labels:  mock, phpunit
Mockery
Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succinct API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL).
Stars: ✭ 10,048 (+12153.66%)
Mutual labels:  mock, phpunit
Guzzler
Supercharge your app or SDK with a testing library specifically for Guzzle
Stars: ✭ 272 (+231.71%)
Mutual labels:  mock, phpunit
Easy Mock
A persistent service that generates mock data quickly and provids visualization view.
Stars: ✭ 8,644 (+10441.46%)
Mutual labels:  mock
Backbone Faux Server
A framework for mocking up server-side persistence / processing for Backbone.js
Stars: ✭ 55 (-32.93%)
Mutual labels:  mock
Moka
A Go mocking framework.
Stars: ✭ 53 (-35.37%)
Mutual labels:  mock
Mocha
Mocha is a mocking and stubbing library for Ruby
Stars: ✭ 1,065 (+1198.78%)
Mutual labels:  mock
Foxman
🍥 an extensible mock server
Stars: ✭ 76 (-7.32%)
Mutual labels:  mock
Openapi Mock Generator
Progressive Web App for generating mocked data from an OpenAPI specification
Stars: ✭ 72 (-12.2%)
Mutual labels:  mock
Designpattern
设计模式
Stars: ✭ 66 (-19.51%)
Mutual labels:  phpunit
Mockswift
MockSwift is a Mock library written in Swift.
Stars: ✭ 56 (-31.71%)
Mutual labels:  mock
Logginginterceptor
An OkHttp interceptor which has pretty logger for request and response. +Mock support
Stars: ✭ 1,149 (+1301.22%)
Mutual labels:  mock
Vue3 Admin
👏vue3.0后台管理框架👏基于vue-cli4+compositionAPI+vue-router4
Stars: ✭ 54 (-34.15%)
Mutual labels:  mock
Gock
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
Stars: ✭ 1,185 (+1345.12%)
Mutual labels:  mock
Timex
A test-friendly replacement for golang's time package
Stars: ✭ 53 (-35.37%)
Mutual labels:  mock
Sublime Phpunit
PHPUnit support for Sublime Text
Stars: ✭ 63 (-23.17%)
Mutual labels:  phpunit
Go Dynamock
Amazon Dynamo DB Mock Driver for Golang to Test Database Interactions
Stars: ✭ 71 (-13.41%)
Mutual labels:  mock
Laravel Json Schema Assertions
JSON Schema assertions for the Laravel framework
Stars: ✭ 61 (-25.61%)
Mutual labels:  phpunit
Antd Admin
An excellent front-end solution for enterprise applications built upon Ant Design and UmiJS
Stars: ✭ 8,678 (+10482.93%)
Mutual labels:  mock

Mock Web Server

Latest Stable Version License Scrutinizer Code Quality Build Status Build Status

Simple, easy to use Mock Web Server for PHP unit testing. Gets along simply with PHPUnit and other unit testing frameworks.

Unit testing HTTP requests can be difficult, especially in cases where injecting a request library is difficult or not ideal. This helps greatly simplify the process.

Mock Web Server creates a local Web Server you can make predefined requests against.

Limitations

Unfortunately, Mock Web Server does not currently support Windows. While it may work in the Linux Subsystem, I do not have a copy of Windows 10 to experiment with.

I would be happy to accept pull requests that correct this.

Documentation

See: docs/docs.md

Requirements

  • php: >=5.4
  • ext-sockets: *
  • ext-json: *
  • ralouphie/getallheaders: ~2.0 || ~3.0

Installing

Install the latest version with:

composer require --dev 'donatj/mock-webserver'

Examples

Basic Usage

The following example shows the most basic usage. If you do not define a path, the server will simply bounce a JSON body describing the request back to you.

<?php

use donatj\MockWebServer\MockWebServer;

require __DIR__ . '/../vendor/autoload.php';

$server = new MockWebServer;
$server->start();

$url = $server->getServerRoot() . '/endpoint?get=foobar';

echo "Requesting: $url\n\n";
echo file_get_contents($url);

Outputs:

Requesting: http://127.0.0.1:61874/endpoint?get=foobar

{
    "_GET": {
        "get": "foobar"
    },
    "_POST": [],
    "_FILES": [],
    "_COOKIE": [],
    "HEADERS": {
        "Host": "127.0.0.1:61874",
        "Connection": "close"
    },
    "METHOD": "GET",
    "INPUT": "",
    "PARSED_INPUT": [],
    "REQUEST_URI": "\/endpoint?get=foobar",
    "PARSED_REQUEST_URI": {
        "path": "\/endpoint",
        "query": "get=foobar"
    }
}

Simple

<?php

use donatj\MockWebServer\MockWebServer;
use donatj\MockWebServer\Response;

require __DIR__ . '/../vendor/autoload.php';

$server = new MockWebServer;
$server->start();

// We define the servers response to requests of the /definedPath endpoint
$url = $server->setResponseOfPath(
	'/definedPath',
	new Response(
		'This is our http body response',
		[ 'Cache-Control' => 'no-cache' ],
		200
	)
);

echo "Requesting: $url\n\n";

$content = file_get_contents($url);

// $http_response_header is a little known variable magically defined
// in the current scope by file_get_contents with the response headers
echo implode("\n", $http_response_header) . "\n\n";
echo $content . "\n";

Outputs:

Requesting: http://127.0.0.1:61880/definedPath

HTTP/1.0 200 OK
Host: 127.0.0.1:61880
Date: Fri, 15 Jan 2021 15:43:40 GMT
Connection: close
X-Powered-By: PHP/7.3.25
Cache-Control: no-cache
Content-type: text/html; charset=UTF-8

This is our http body response

PHPUnit

<?php

use donatj\MockWebServer\MockWebServer;
use donatj\MockWebServer\Response;

class ExampleTest extends PHPUnit_Framework_TestCase {

	/** @var MockWebServer */
	protected static $server;

	public static function setUpBeforeClass() {
		self::$server = new MockWebServer;
		self::$server->start();
	}

	public function testGetParams() {
		$result  = file_get_contents(self::$server->getServerRoot() . '/autoEndpoint?foo=bar');
		$decoded = json_decode($result, true);
		$this->assertSame('bar', $decoded['_GET']['foo']);
	}

	public function testGetSetPath() {
		// $url = http://127.0.0.1:8123/definedEndPoint
		$url    = self::$server->setResponseOfPath('/definedEndPoint', new Response('foo bar content'));
		$result = file_get_contents($url);
		$this->assertSame('foo bar content', $result);
	}

	static function tearDownAfterClass() {
		// stopping the web server during tear down allows us to reuse the port for later tests
		self::$server->stop();
	}

}

Multiple Responses from the Same Endpoint

Response Stack

If you need an ordered set of responses, that can be done using the ResponseStack.

<?php

use donatj\MockWebServer\MockWebServer;
use donatj\MockWebServer\Response;
use donatj\MockWebServer\ResponseStack;

require __DIR__ . '/../vendor/autoload.php';

$server = new MockWebServer;
$server->start();

// We define the servers response to requests of the /definedPath endpoint
$url = $server->setResponseOfPath(
	'/definedPath',
	new ResponseStack(
		new Response("Response One"),
		new Response("Response Two")
	)
);

echo "Requesting: $url\n\n";

$contentOne = file_get_contents($url);
$contentTwo = file_get_contents($url);
// This third request is expected to 404 which will error if errors are not ignored
$contentThree = file_get_contents($url, false, stream_context_create([ 'http' => [ 'ignore_errors' => true ] ]));

// $http_response_header is a little known variable magically defined
// in the current scope by file_get_contents with the response headers
echo $contentOne . "\n";
echo $contentTwo . "\n";
echo $contentThree . "\n";

Outputs:

Requesting: http://127.0.0.1:61886/definedPath

Response One
Response Two
Past the end of the ResponseStack

Response by Method

If you need to vary responses to a single endpoint by method, you can do that using the ResponseByMethod response object.

<?php

use donatj\MockWebServer\MockWebServer;
use donatj\MockWebServer\Response;
use donatj\MockWebServer\ResponseByMethod;

require __DIR__ . '/../vendor/autoload.php';

$server = new MockWebServer;
$server->start();


// Create a response for both a POST and GET request to the same URL

$response = new ResponseByMethod([
	ResponseByMethod::METHOD_GET  => new Response("This is our http GET response"),
	ResponseByMethod::METHOD_POST => new Response("This is our http POST response", [], 201),
]);

$url = $server->setResponseOfPath('/foo/bar', $response);

foreach( [ ResponseByMethod::METHOD_GET, ResponseByMethod::METHOD_POST ] as $method ) {
	echo "$method request to $url:\n";

	$context = stream_context_create([ 'http' => [ 'method' => $method ] ]);
	$content = file_get_contents($url, false, $context);

	echo $content . "\n\n";
}

Outputs:

GET request to http://127.0.0.1:61894/foo/bar:
This is our http GET response

POST request to http://127.0.0.1:61894/foo/bar:
This is our http POST response

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].