The aim of this project is to mock the microservices responses that your service depends on. By this way you will not need that third party services will be up and running in order to test and develop your microservice, because each time that you request some data to this APIs you will get a mock response.
http://gopkg.in/pjgg/rest-in-peace.v0
- Define MockServer port
const mockServerPort = 8080
- Get a singleton instance of your MockServer
mockServer = Instance(mockServerPort)
- Clean your stubs each time that you run a test
mockServer.CleanStub()
- define your test stubs
outboundJSON := []byte(`{"key":"hello","value":"world"}`)
mockServer.When(GET, "/v1/service/hello*").ThenReturn(outboundJSON, 200)
This library needs from other libraries in order to build and orchestrate your unit/integration test. I will provide an integration example using testify.
- Define your test suit struct
type mockServerSuite struct {
suite.Suite
mockServer MockServerBehavior
jsonAssert jsonAssert.JsonAssert
}
- Setup testify main function and instanciate your mockServer
const mockServerPort = 8080
func TestMockServerSuite(t *testing.T) {
testSuit := new(mockServerSuite)
testSuit.mockServer = Instance(mockServerPort)
testSuit.jsonAssert = jsonAssert.Instance()
suite.Run(t, testSuit)
}
- Define your test setup, the code that must be run before each test.
func (testSuit *mockServerSuite) SetupTest() {
// Remember clean the stubs everytime that you run a test
testSuit.mockServer.CleanStub()
}
- Write down your unit test
func (testSuit *mockServerSuite) TestHelloWorld() {
var err error
var resp *http.Response
outboundJSON := []byte(`{"key":"hello","value":"world"}`)
testSuit.mockServer.When(GET, "/v1/service/hello*").ThenReturn(outboundJSON, 200)
// Your service as myService.method() or a simple httpRequest
req, _ := newHTTPRequest("GET", "http://localhost:8080/v1/service/hello/", nil, nil)
// assert your response.
if resp, err = makeHTTPQuery(req); err == nil {
data, _ := ioutil.ReadAll(resp.Body)
// You could use restInPeace jsonAssert or testify asserts or your favorite assert lib
assert.Nil(testSuit.T(), testSuit.jsonAssert.AssertJsonEquals(outboundJSON, data), "Unexpected error")
assert.Equal(testSuit.T(), 200, resp.StatusCode)
}
if err != nil {
testSuit.Fail("Unexpected error", err.Error())
}
}