Skip to content

YReshetko/mock-server-client

Repository files navigation

Test client for MockServer

This is the go client with testing package integration to mock server:

How to use

Run examples

make docker-up
make examples 

Write tests

  1. Make sure mock server is up and running on some host (for example localhost:1080)
  2. Initiate MockServer to start using the mock:
import (
	...
    msc "github.com/YReshetko/mock-server-client"
	...
)

func TestSomething(t *testing.T) {
    mock := msc.NewMockServer(
		msc.Config{
            Host:    "localhost",
            Port:    1080,
            Verbose: true,
        },
    )
	...
}
  1. At some point, before you expect your system calls third party service that you are going to mock, setup expectations. For example:
func TestSomething(t *testing.T) {
	...
    expectRequest := SomeRequest{}
    expectation := mock.On(http.SomeMethod, "/some/{some_param}/endpoint").
        Request(
            msc.WithPathParameter("some_param", "[0-9]{1}"),
        ).
        SequentialResponse(
            msc.WithStatusCode(http.StatusCreated),
        ).
        SequentialResponse(
            msc.WithStatusCode(http.StatusOK),
        ).
        DefaultResponse(
            msc.WithStatusCode(http.StatusNotFound),
        ).
        NumCalls(3).
        AssertionAtCall(0, msc.NewAssertion().
            WithJsonBody(&expectRequest).
            AddHeader("User-Agent", "Go-http-client/1.1").
            WithPath("/some/1/endpoint"),
        )
    mock.Setup(context.Background(), expectation)
	...
}
  1. When your system did some work, and you are going to verify sent requests to the mocked third party you need to call Veryfy or VerifyExpectation method. At this point all expected bodies that were setup in assertions will be fulfilled by the MockServer:
func TestSomething(t *testing.T) {
	...
	mock.Verify(context.Background(), t)
	assert.Equal(t, "some-field-value", expectRequest.SomeField)
	...
}
  1. The most important thing is to reset MockServer each time when you start new test scenario, otherwise all previously created expectation can affect verification result. Remember if you create a new MockServer it doesn't mean that you have cleaned the expectation on mock server app.
func TestSomething(t *testing.T) {
	...
	mock.Reset(context.Background())
	...
}