|
1 | 1 | # RestClient.Net |
2 | 2 |
|
3 | | - |
| 3 | + |
4 | 4 |
|
5 | 5 | **The safest way to make REST calls in C#** |
6 | 6 |
|
@@ -137,6 +137,8 @@ Matched: Ok<Post, HttpError<ErrorResponse>>, Error<Post, HttpError<ErrorResponse |
137 | 137 | Missing: Error<Post, HttpError<ErrorResponse>> with ExceptionError<ErrorResponse> |
138 | 138 | ``` |
139 | 139 |
|
| 140 | + |
| 141 | + |
140 | 142 | Your build fails until you handle all cases. This is the difference between **runtime crashes** and **compile-time safety**. |
141 | 143 |
|
142 | 144 | ### Installing Exhaustion Without RestClient.Net |
@@ -279,6 +281,43 @@ var result = await httpClient.PostAsync<UploadResponse, string>( |
279 | 281 | ); |
280 | 282 | ``` |
281 | 283 |
|
| 284 | +## Testing with Mock HttpClient |
| 285 | + |
| 286 | +Mock `HttpClient` by creating a fake `IHttpClientFactory` with pattern-matched responses: |
| 287 | + |
| 288 | +```csharp |
| 289 | +var factory = FakeHttpClientFactory.CreateMockHttpClientFactory( |
| 290 | + response: null, // Use pattern matching for dynamic responses |
| 291 | + onRequestSent: request => |
| 292 | + { |
| 293 | + // Assert request properties |
| 294 | + Assert.Equal("Bearer token", request.Headers.Authorization?.Parameter); |
| 295 | + } |
| 296 | +); |
| 297 | + |
| 298 | +// The handler returns responses based on method + URI patterns: |
| 299 | +// GET /posts -> 200 OK with post JSON |
| 300 | +// POST /posts -> 201 Created |
| 301 | +// PUT /posts/1 -> 200 OK |
| 302 | +// DELETE /posts/1 -> 200 OK |
| 303 | +// * -> 404 Not Found |
| 304 | +
|
| 305 | +var httpClient = factory.CreateClient(); |
| 306 | +var result = await httpClient.GetAsync<Post, ErrorResponse>(/* ... */); |
| 307 | + |
| 308 | +// Test with exceptions |
| 309 | +var exFactory = FakeHttpClientFactory.CreateMockHttpClientFactory( |
| 310 | + exceptionToThrow: new HttpRequestException("Network error") |
| 311 | +); |
| 312 | + |
| 313 | +// Test with simulated delays |
| 314 | +var delayFactory = FakeHttpClientFactory.CreateMockHttpClientFactory( |
| 315 | + simulatedDelay: TimeSpan.FromMilliseconds(500) |
| 316 | +); |
| 317 | +``` |
| 318 | + |
| 319 | +The fake handler uses a switch expression on `(HttpMethod, Uri)` tuples—extend it for your test scenarios. |
| 320 | + |
282 | 321 | ## Upgrading from RestClient.Net 6.x |
283 | 322 |
|
284 | 323 | You can continue to use the V6 `IClient` interface with RestClient .Net 7. RestClient.Net 7 is a complete rewrite with a functional architecture. For existing v6 users, **RestClient.Net.Original** provides a polyfill that implements the v6 `IClient` interface using v7 under the hood. |
|
0 commit comments