|
| 1 | +The general consensus when writing tests is that you should avoid making real HTTP requests when running your tests. Instead, you should use a mock server or a fake client. |
| 2 | + |
| 3 | +## Mocking HTTP Responses |
| 4 | + |
| 5 | +The mocking feature of `Async::HTTP` uses a real server running in a separate task, and routes all requests to it. This allows you to intercept requests and return custom responses, but still use the real HTTP client. |
| 6 | + |
| 7 | +In order to enable this feature, you must create an instance of class `Async::HTTP::Mock::Endpoint` which will handle the requests. |
| 8 | + |
| 9 | +```ruby |
| 10 | +require 'async/http' |
| 11 | +require 'async/http/mock' |
| 12 | + |
| 13 | +mock_endpoint = Async::HTTP::Mock::Endpoint.new |
| 14 | + |
| 15 | +Sync do |
| 16 | + # Start a background server: |
| 17 | + server_task = Async(transient: true) do |
| 18 | + mock_endpoint.run do |request| |
| 19 | + # Respond to the request: |
| 20 | + ::Protocol::HTTP::Response[200, {}, ["Hello, World"]] |
| 21 | + end |
| 22 | + end |
| 23 | + |
| 24 | + endpoint = Async::HTTP::Endpoint.parse("https://www.google.com") |
| 25 | + mocked_endpoint = mock_endpoint.wrap(endpoint) |
| 26 | + client = Async::HTTP::Client.new(mocked_endpoint) |
| 27 | + |
| 28 | + response = client.get("/") |
| 29 | + puts response.read |
| 30 | + # => "Hello, World" |
| 31 | +end |
| 32 | +``` |
| 33 | + |
| 34 | +## Transparent Mocking |
| 35 | + |
| 36 | +Using your test framework's mocking capabilities, you can easily replace the `Async::HTTP::Client#new` with a method that returns a client with a mocked endpoint. |
| 37 | + |
| 38 | +### Sus Integration |
| 39 | + |
| 40 | +```ruby |
| 41 | +require 'async/http' |
| 42 | +require 'async/http/mock' |
| 43 | +require 'sus/fixtures/async/reactor_context' |
| 44 | + |
| 45 | +include Sus::Fixtures::Async::ReactorContext |
| 46 | + |
| 47 | +let(:mock_endpoint) {Async::HTTP::Mock::Endpoint.new} |
| 48 | + |
| 49 | +def before |
| 50 | + super |
| 51 | + |
| 52 | + # Mock the HTTP client: |
| 53 | + mock(Async::HTTP::Client) do |mock| |
| 54 | + mock.wrap(:new) do |original, endpoint| |
| 55 | + original.call(mock_endpoint.wrap(endpoint)) |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + # Run the mock server: |
| 60 | + Async(transient: true) do |
| 61 | + mock_endpoint.run do |request| |
| 62 | + ::Protocol::HTTP::Response[200, {}, ["Hello, World"]] |
| 63 | + end |
| 64 | + end |
| 65 | +end |
| 66 | + |
| 67 | +it "should perform a web request" do |
| 68 | + client = Async::HTTP::Client.new(Async::HTTP::Endpoint.parse("https://www.google.com")) |
| 69 | + response = client.get("/") |
| 70 | + # The response is mocked: |
| 71 | + expect(response.read).to be == "Hello, World" |
| 72 | +end |
| 73 | +``` |
0 commit comments