golangmockserver

package module
v1.1.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 6, 2021 License: MIT Imports: 6 Imported by: 0

README

Documentation Go Report Card license Release

Golang MockServer is a wrapper around httptest.Server and provides helpers to mock out HTTP request/responses

see Examples_test.go for example usage

// Create a new mock http server and pass in the methods you want it to match
mockServer := NewMockServer([]*MockServerRequest{
    {
        Uri:      "/foo",
        Method:   "GET",
    },
})
defer mockServer.Close()

//Make request to the mock server
// uses mockServer.BaseUrl() to make the call to the localhost server
request, _ := http.NewRequest("GET", mockServer.BaseUrl() + "/foo", nil)
client := &http.Client {}

response, _ := client.Do(request)

//validate responses
assert.Equal(t, 200, response.StatusCode)

Inspired by: https://www.mock-server.com

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MockServer added in v1.1.0

type MockServer struct {
	// contains filtered or unexported fields
}

MockServer is a mock http server

func NewMockServer added in v1.1.0

func NewMockServer(mockedRequests []*MockServerRequest) *MockServer

NewMockServer creates a new Mock server with mocked requests

Example

Basic example matches the route GET /foo and returns a 200

//Setup
mockServer := NewMockServer([]*MockServerRequest{
	{
		URI:    "/foo",
		Method: "GET",
	},
})
defer mockServer.Close()

//Make request to the mock server
request, _ := http.NewRequest("GET", mockServer.BaseURL()+"/foo", nil)
client := &http.Client{}

_, _ = client.Do(request)
Output:

Example (HeaderMatch)

This example show how a match based on a header only returns 200 when the header matches. The first request responds with a 404 because the header isn't set.

mockServer := NewMockServer([]*MockServerRequest{
	{
		URI:    "/foo",
		Method: "GET",
		Headers: map[string]string{
			"Authorization": "basic .*",
		},
		Response: &MockServerResponse{
			StatusCode: 200,
		},
	},
})
defer mockServer.Close()

request, _ := http.NewRequest("GET", mockServer.BaseURL()+"/foo", nil)

client := &http.Client{}

client.Do(request)
//returns 404

request, _ = http.NewRequest("GET", mockServer.BaseURL()+"/foo", nil)
request.Header.Add("Authorization", "basic adfljkasdlfj")
//returns 200
Output:

Example (RequestBodyMatching)
mockServer := NewMockServer([]*MockServerRequest{
	{
		URI:    "/foo",
		Method: "GET",
		Response: &MockServerResponse{
			StatusCode: 500,
		},
	},
	{
		URI:    "/foo",
		Method: "GET",
		Body:   []byte("hello world"),
		Response: &MockServerResponse{
			StatusCode: 201,
		},
	},
})
defer mockServer.Close()

bodyData := bytes.NewReader([]byte("hello world"))
request, _ := http.NewRequest("GET", mockServer.BaseURL()+"/foo", bodyData)
client := &http.Client{}

client.Do(request)
Output:

Example (ResponseHeaders)

In this example the foo response header is returned.

mockServer := NewMockServer([]*MockServerRequest{
	{
		URI:    "/foo",
		Method: "GET",
		Response: &MockServerResponse{
			Headers: map[string]string{
				"foo": "bar",
			},
		},
	},
})
defer mockServer.Close()

request, _ := http.NewRequest("GET", mockServer.BaseURL()+"/foo", nil)
client := &http.Client{}

client.Do(request)
Output:

Example (UriNotFound)

A 404 is returned when there aren't any matching URIs

mockServer := NewMockServer([]*MockServerRequest{
	{
		URI:    "/foo",
		Method: "GET",
	},
})
defer mockServer.Close()

request, _ := http.NewRequest("GET", mockServer.BaseURL()+"/bar", nil)
client := &http.Client{}

client.Do(request)
//Returns a 404
Output:

func (*MockServer) BaseURL added in v1.1.0

func (s *MockServer) BaseURL() string

BaseURL gets the localhost base url to call

func (*MockServer) Close added in v1.1.0

func (s *MockServer) Close()

Close shuts down the mock http server

func (*MockServer) Requests added in v1.1.0

func (s *MockServer) Requests() []*MockServerRequest

Requests gets the configured requests

type MockServerRequest added in v1.1.0

type MockServerRequest struct {
	//The URI to match
	URI string
	//The HTTP method to match (GET, PUT, POST, etc)
	Method string
	//Optional: The Body to match against
	Body interface{}
	//Optional: Any headers to match against.  Header values can be a regex
	Headers map[string]string

	//Optional: Any querystring parameters to match against.  Parameter values can be a regex
	QueryParameters map[string]string

	//Optional: Response to send from the matched request
	Response *MockServerResponse

	//Optional: Maximum number of times to match this request
	MaxMatchCount int
	// contains filtered or unexported fields
}

MockServerRequest is a mocked request to the server

func (*MockServerRequest) InvokeCount added in v1.1.0

func (m *MockServerRequest) InvokeCount() int

Invoke count returns the number of times this request was invoked

type MockServerResponse added in v1.1.0

type MockServerResponse struct {
	//Optional: HTTP status code to return, default is 200
	StatusCode int
	//Optional: body to return, default is nil
	Body interface{}
	//Optional: Additional headers to return, default is none
	Headers map[string]string
}

MockServerResponse is the response from a mocked request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL