3.78Simulating Request Responses and Exceptions (Mock)
Created on Aug 17, 2026~4 min read
MockResponse and MockException are designed specifically for unit testing. They let you directly return a preset response or throw a preset exception without actually sending an HTTP request, with zero intrusion into business code.
// Simulate a JSON response (auto-serialized)HttpRequestBuilder.Get("https://api.furion.net/weather") .MockResponse(new { Temperature = 25, Condition = "Sunny" });// Simulate a custom status code and content typeHttpRequestBuilder.Post("https://api.furion.net/upload") .MockResponse(new { Id = 123 }, HttpStatusCode.Created, "application/json");// Simulate a complete HttpResponseMessage (for complex scenarios such as file streams)var content = new StreamContent(File.OpenRead("test.pdf"));content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };HttpRequestBuilder.Get("https://example.com/download") .MockResponse(response);// Simulate an exception (timeout, network interruption, etc.)HttpRequestBuilder.Get("https://api.furion.net/data") .MockException(new HttpRequestException("Connection timed out"));// Clear all mock settingsHttpRequestBuilder.Get("https://api.furion.net/data") .MockResponse(new { }) .ClearMock(); // After clearing, the request will be sent normallyWhen combined with HttpRemoteService, this feature can completely replace real network requests, greatly improving the isolation and execution speed of unit tests.