|
1 | 1 | # Devlead.Testing.MockHttp
|
2 | 2 |
|
3 |
| -.NET Library for mocking HTTP client requests |
| 3 | +Opinionated .NET source package for mocking HTTP client requests |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +```bash |
| 8 | +dotnet add package Devlead.Testing.MockHttp |
| 9 | +``` |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +### Configuration |
| 14 | + |
| 15 | +The `Routes.json` file is used to configure the mock HTTP client responses. It defines the routes, HTTP methods, URIs, optional headers, and authentication requirements. Each route specifies the expected request and the corresponding response, including content type, status code, and any required authorization. |
| 16 | + |
| 17 | +### Embedded Resources |
| 18 | + |
| 19 | +The `Routes.json` file, along with other resources like `Index.txt` and `Secret.json`, are included as embedded resources in the project. This allows them to be accessed at runtime for simulating HTTP responses. These resources are configured in the `.csproj` file under `<EmbeddedResource>` tags. |
| 20 | + |
| 21 | +### Example Configuration |
| 22 | + |
| 23 | +#### Routes.json |
| 24 | + |
| 25 | +```json |
| 26 | +[ |
| 27 | + { |
| 28 | + "Request": { |
| 29 | + "Methods": [ |
| 30 | + { |
| 31 | + "Method": "GET" |
| 32 | + } |
| 33 | + ], |
| 34 | + "AbsoluteUri": "https://example.com/login/secret.json" |
| 35 | + }, |
| 36 | + "Responses": [ |
| 37 | + { |
| 38 | + "RequestHeaders": {}, |
| 39 | + "ContentResource": "Example.Login.Secret.json", |
| 40 | + "ContentType": "application/json", |
| 41 | + "ContentHeaders": {}, |
| 42 | + "StatusCode": 200 |
| 43 | + } |
| 44 | + ], |
| 45 | + "Authorization": { |
| 46 | + "Authorization": [ |
| 47 | + "Bearer AccessToken" |
| 48 | + ] |
| 49 | + } |
| 50 | + }, |
| 51 | + { |
| 52 | + "Request": { |
| 53 | + "Methods": [ |
| 54 | + { |
| 55 | + "Method": "GET" |
| 56 | + } |
| 57 | + ], |
| 58 | + "AbsoluteUri": "https://example.com/index.txt" |
| 59 | + }, |
| 60 | + "Responses": [ |
| 61 | + { |
| 62 | + "RequestHeaders": {}, |
| 63 | + "ContentResource": "Example.Index.txt", |
| 64 | + "ContentType": "text/plain", |
| 65 | + "ContentHeaders": {}, |
| 66 | + "StatusCode": 200 |
| 67 | + } |
| 68 | + ] |
| 69 | + } |
| 70 | +] |
| 71 | +``` |
| 72 | + |
| 73 | +#### Example Resource Files |
| 74 | + |
| 75 | +- **Index.txt**: Contains plain text data used in responses. |
| 76 | + |
| 77 | +```plaintext |
| 78 | +Hello, World! |
| 79 | +``` |
| 80 | + |
| 81 | +- **Secret.json**: Contains JSON data representing a user, used in responses. |
| 82 | + |
| 83 | +```json |
| 84 | +{ |
| 85 | + "Login": "johdoe", |
| 86 | + "FirstName": "John", |
| 87 | + "LastName": "Doe" |
| 88 | +} |
| 89 | +``` |
| 90 | + |
| 91 | +### Project Configuration |
| 92 | + |
| 93 | +In the `.csproj` file, these resources are specified as embedded resources: |
| 94 | + |
| 95 | +```xml |
| 96 | +<ItemGroup> |
| 97 | + <EmbeddedResource Include="Resources\Example\Index.txt" /> |
| 98 | + <EmbeddedResource Include="Resources\Routes.json" /> |
| 99 | + <EmbeddedResource Include="Resources\Example\Login\Secret.json" /> |
| 100 | +</ItemGroup> |
| 101 | +``` |
| 102 | + |
| 103 | +These configurations enable the mock HTTP client to simulate real HTTP requests and responses, facilitating testing without actual network calls. |
| 104 | + |
| 105 | +### Registering and Using the Mock HTTP Client |
| 106 | + |
| 107 | +The mock HTTP client is registered using dependency injection in the `ServiceProviderFixture.cs` file. This setup allows for simulating HTTP requests and responses in a controlled test environment. |
| 108 | + |
| 109 | +#### Registration |
| 110 | + |
| 111 | +Create a class called `ServiceProviderFixture.cs` without name space and implement the partial method: |
| 112 | + |
| 113 | +```csharp |
| 114 | +public static partial class ServiceProviderFixture |
| 115 | +{ |
| 116 | + static partial void InitServiceProvider(IServiceCollection services) |
| 117 | + { |
| 118 | + services.AddSingleton<MyService>() |
| 119 | + .AddMockHttpClient<Constants>(); |
| 120 | + } |
| 121 | +} |
| 122 | +``` |
| 123 | + |
| 124 | +The `AddMockHttpClient<Constants>()` method configures the HTTP client for use in tests. Here, `Constants` is a type that serves as a parent to the resources configuration, encapsulating settings and paths for the mock HTTP client to use during testing. |
| 125 | + |
| 126 | +#### Usage in Tests |
| 127 | + |
| 128 | +- **HttpClientTests.cs**: The mock HTTP client is used to perform HTTP GET requests, and the responses are verified. |
| 129 | + |
| 130 | +```csharp |
| 131 | +public class HttpClientTests |
| 132 | +{ |
| 133 | + [Test] |
| 134 | + public async Task GetAsync() |
| 135 | + { |
| 136 | + var httpClient = ServiceProviderFixture.GetRequiredService<HttpClient>(); |
| 137 | + var response = await httpClient.GetAsync("https://example.com/index.txt"); |
| 138 | + await Verify(response); |
| 139 | + } |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +- **MyServiceTests.cs**: The mock HTTP client is used within the `MyService` class to test various scenarios, including unauthorized and authorized access. |
| 144 | + |
| 145 | +```csharp |
| 146 | +public class MyServiceTests |
| 147 | +{ |
| 148 | + [Test] |
| 149 | + public async Task GetSecret() |
| 150 | + { |
| 151 | + var myService = ServiceProviderFixture.GetRequiredService<MyService>( |
| 152 | + configure => configure.ConfigureMockHttpClient<Constants>( |
| 153 | + client => client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( |
| 154 | + "Bearer", |
| 155 | + "AccessToken" |
| 156 | + ) |
| 157 | + ) |
| 158 | + ); |
| 159 | + var result = await myService.GetSecret(); |
| 160 | + await Verify(result); |
| 161 | + } |
| 162 | +} |
| 163 | +``` |
| 164 | + |
| 165 | +This approach ensures that your service logic is tested in isolation, without making actual network requests, by simulating HTTP interactions using the mock HTTP client. The `Constants` type helps manage the configuration of these interactions, providing a centralized way to define and access resource settings. |
| 166 | + |
| 167 | + |
| 168 | +## Example project |
| 169 | + |
| 170 | +A real world example can be found in the [Blobify](https://github.com/devlead/Blobify) project. |
0 commit comments