Mock level up

Mocker un serveur avec Wiremock

Don't mock what you don't own.

– Quelqu'un de bien

Cas d'une API web

Client

  • framework de mock
  • Guzzle mock handler
  • Httplug
  • ...

Serveur

  • wiremock
  • mockserver
  • postman
  • ...

2 possibilités

  • pas notre interface
  • bruit dans les tests
  • trop flexible ?

InconvéniEnts

  • hyper flexible
  • facile
  • ?

Avantages

Cas d'une API web

Client

  • moins flexible
  • stub uniquement ?

InconvéniEnts

  • client testé
  • tests propres
  • pas si compliqué
  • découplage du client

Avantages

Cas d'une API web

Serveur

  • Java ++
  • image docker officielle
  • configurable (HTTPS, proxy ...)

Wiremock

Installation

Wiremock

Stub

{
    "request": {
        "method": "GET",
        "url": "/body-file"
    },
    "response": {
        "status": 200,
        "bodyFileName": "path/to/myfile.xml"
    }
}

Wiremock

Request matching

{
  "request" : {
    "urlPath" : "/everything",
    "method" : "ANY",
    "headers" : {
      "Accept" : {
        "contains" : "xml"
      }
    },
    "queryParameters" : {
      "search_term" : {
        "equalTo" : "WireMock"
      }
    },
    "cookies" : {
      "session" : {
        "matches" : ".*12345.*"
      }
    },
    "bodyPatterns" : [ {
      "equalToXml" : "<search-results />"
    }, {
      "matchesXPath" : "//search-results"
    } ],
    "multipartPatterns" : [ {
      "matchingType" : "ANY",
      "headers" : {
        "Content-Disposition" : {
          "contains" : "name=\"info\""
        },
        "Content-Type" : {
          "contains" : "charset"
        }
      },
      "bodyPatterns" : [ {
        "equalToJson" : "{}"
      } ]
    } ],
    "basicAuthCredentials" : {
      "username" : "jeff@example.com",
      "password" : "jeffteenjefftyjeff"
    }
  },
  "response" : {
    "status" : 200
  }
}

Wiremock

Scenarios

  • simuler les interactions
  • machine à états
{
  "scenarioName": "To do list",
  "requiredScenarioState": "Started",
  "newScenarioState": "Cancel newspaper item added",
  "request": {
    "method": "POST",
    "url": "/todo/items",
    "bodyPatterns": [
    	{ "contains": "Cancel newspaper subscription" }
    ]
  },
  "response": {
  	"status": 201
  }
}

Wiremock

Bonus

  • proxy
  • record / replay
  • response templating
  • simulate faults
  • webhooks

Wiremock

By Karim PINCHON

Wiremock

  • 541