Skip to content

pjgg/rest-in-peace

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rest-in-peace

Build Status codecov

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.

Basic Usage

Install

http://gopkg.in/pjgg/rest-in-peace.v0

How to use

  1. Define MockServer port
const mockServerPort = 8080 
  1. Get a singleton instance of your MockServer
mockServer = Instance(mockServerPort)
  1. Clean your stubs each time that you run a test
mockServer.CleanStub()
  1. define your test stubs
outboundJSON := []byte(`{"key":"hello","value":"world"}`)
mockServer.When(GET, "/v1/service/hello*").ThenReturn(outboundJSON, 200)

Testify Integration example

This library needs from other libraries in order to build and orchestrate your unit/integration test. I will provide an integration example using testify.

  1. Define your test suit struct
type mockServerSuite struct {
	suite.Suite
	mockServer MockServerBehavior
	jsonAssert jsonAssert.JsonAssert
}
  1. 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)
}
  1. 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()
}
  1. 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())
	}

}