danskernesdigitalebibliotek / behat-wiremock-extension

A Behat extension for mocking HTTP requests

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

behat-wiremock-extension

Build Status

This is an extension which integrates Wiremock, a simulator for HTTP-based APIs, with Behat, a Behavior-Driven Development framework for PHP.

The extension lets developers instrument Wiremock and control which responses should be returned for what requests using the Wiremock admin API.

The extension was originally developed by Vitalii Piskovyi and has since been modernized by Det Digitale Folkebibliotek, resort for applications in the national infrastructure for libraries in Denmark.

Usage

Configuration

default:
  extensions:
    VPX\WiremockExtension\ServiceContainer\WiremockExtension:
        # Url to Wiremock
        base_url: http://localhost:8080
        # Base path for mapping files
        mapping_path: "%paths.base%/tests/Resources/fixtures"
        # Mappings which must be loaded automatically for every test
        preload_mappings:
          - { service: foo, mapping: bar.json }
  suites:
    default:
      contexts:
        - VPX\WiremockExtension\Context\WiremockContext

Mappings

Developers can provide a JSON file containing mappings of requests and responses to instrument Wiremock.

# app.feature
@wiremock-reset
Feature: Wiremock

  Scenario: Trying to load /path/to/awesome/method2
    Given the following services exist with mappings:
      | service | mapping  |
      | baz     | qux.json |
    When I am on "http://localhost:8080/path/to/awesome/method2"
    Then the response status code should be 200
    And the response should contain "{\"success\":true}"
    When I am on "http://localhost:8080/path/to/awesome/method"
    Then the response status code should be 201
    And the response should contain "{\"success\":true}"

Direct instrumentation

Developers can instrument Wiremock in a context by implementing the WiremockAwareInterface interface and using the WiremockAware trait.

Instrumentation features are provided through an instance of the Wiremock client provided by the wiremock-php library.

use VPX\WiremockExtension\Context\WiremockAware;
use VPX\WiremockExtension\Context\WiremockAwareInterface;
use WireMock\Client\WireMock;

class FeatureContext implements WiremockAwareInterface {
    use WiremockAware;

    /**
     * @Given a response is mocked
     */
    public function assertMockedResponse() {
        $this->getWiremock()->stubFor(
            WireMock::get(
                WireMock::urlPathEqualTo("/path/to/awesome/method3")
            )
                ->willReturn(WireMock::aResponse()
                    ->withBody(json_encode([
                    "success" => true
                ]))
            )
        );
    }
}

About

A Behat extension for mocking HTTP requests

License:MIT License


Languages

Language:PHP 92.5%Language:Gherkin 5.4%Language:Makefile 2.2%