MockHTTPServer- in the
TestClient. As part of the request handling logic, your application might issue requests to some other server.
MockHTTPServerallows you to validate that the request your application sent was correct and gives you control what the responses are to those requests. For example,
githubMockis an instance of
MockHTTPServerin the following test, which ensures that the request was constructed correctly:
GET /github_profile/fredis sent to your application, that it turns around and searches for a user in GitHub's API. This test ensures that we have correctly translated our request to a request to be made to the GitHub API. If no request was made - because of a programmer error - this test would fail because the
githubMock.next()would never complete. There is no next request, because none was ever delivered!
MockHTTPServeris a 200 OK Response with an empty body. You may change this behavior by queuing responses in a mock server.
queueResponseadds a 200 OK Response to the mock server queue with a specific body. The mock server will send that response for the next request it receives. In the implementation of
/github_profile/fred, your application sends a
GET /users/search?name=fredto the GitHub API - except the GitHub API is your mock server, and it returns the response you queued instead. Thus, the queued up response is the expected response of the GitHub API.
MockHTTPServerand override its
openmethod to add logic to determine the response. Please see the implementation of
MockHTTPServer.openfor more details.
MockHTTPServeris created when setting up tests. It must be closed when tearing down tests. If you use the same mock server to across all tests (e.g., open it in
setUpAll), make sure to clear it after each test:
MockHTTPServerlistens on localhost on a specific port. An application that makes testable external service requests should provide the base URI for those services in a configuration file. The URI for that service in the configuration file used during testing should point at localhost and a specific port. For example, if a deployed
config.yamlfile has the following key-values:
APIConfigurationis an existing type and is meant for this purpose.