Extends Verify to allow verification of Http bits.
See Milestones for release notes.
https://nuget.org/packages/Verify.Http/
Call VerifierSettings.InitializePlugins()
in a [ModuleInitializer]
.
public static class ModuleInitializer
{
[ModuleInitializer]
public static void Initialize() =>
VerifierSettings.InitializePlugins();
}
Or, if order of plugins is important, use VerifyHttp.Initialize()
in a [ModuleInitializer]
.
Enable at any point in a test using VerifyTests.Recording.Start()
.
Includes converters for the following
HttpMethod
Uri
HttpHeaders
HttpContent
HttpRequestMessage
HttpResponseMessage
For example:
[Fact]
public async Task HttpResponse()
{
using var client = new HttpClient();
var result = await client.GetAsync("https://raw.githubusercontent.com/VerifyTests/Verify/main/license.txt");
await Verify(result);
}
{
Status: 200 OK,
Headers: {
Accept-Ranges: bytes,
Access-Control-Allow-Origin: *,
Cache-Control: max-age=300,
Connection: keep-alive,
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox,
Cross-Origin-Resource-Policy: cross-origin,
Strict-Transport-Security: max-age=31536000,
Vary: Authorization,Accept-Encoding,Origin,
Via: 1.1 varnish,
X-Content-Type-Options: nosniff,
X-Frame-Options: deny,
X-XSS-Protection: 1; mode=block
},
Content: {
Headers: {
Content-Type: text/plain; charset=utf-8,
Expires: DateTime_1
},
Value:
MIT License
Copyright (c) .NET Foundation and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
}
Headers are treated as properties, and hence can be ignored using IgnoreMember
:
[Fact]
public async Task IgnoreHeader()
{
using var client = new HttpClient();
using var result = await client.GetAsync("https://raw.githubusercontent.com/VerifyTests/Verify/main/license.txt");
await Verify(result)
.IgnoreMembers("Server");
}
For code that does web calls via HttpClient, these calls can be recorded and verified.
Given a class that does some Http calls:
// Resolve a HttpClient. All http calls done at any
// resolved client will be added to `recording.Sends`
public class MyService(HttpClient client)
{
public Task MethodThatDoesHttp() =>
// Some code that does some http calls
client.GetAsync("https://raw.githubusercontent.com/VerifyTests/Verify/main/license.txt");
}
Http recording can be added to a IHttpClientBuilder
:
var collection = new ServiceCollection();
collection.AddScoped<MyService>();
var httpBuilder = collection.AddHttpClient<MyService>();
// Adds a AddHttpClient and adds a RecordingHandler using AddHttpMessageHandler
var recording = httpBuilder.AddRecording();
await using var provider = collection.BuildServiceProvider();
var myService = provider.GetRequiredService<MyService>();
await myService.MethodThatDoesHttp();
await Verify(recording.Sends);
Http can also be added globally IHttpClientBuilder
:
var collection = new ServiceCollection();
collection.AddScoped<MyService>();
// Adds a AddHttpClient and adds a RecordingHandler using AddHttpMessageHandler
var (builder, recording) = collection.AddRecordingHttpClient();
await using var provider = collection.BuildServiceProvider();
var myService = provider.GetRequiredService<MyService>();
await myService.MethodThatDoesHttp();
await Verify(recording.Sends);
[
{
RequestUri: https://raw.githubusercontent.com/VerifyTests/Verify/main/license.txt,
RequestMethod: GET,
ResponseStatus: OK 200,
ResponseHeaders: {
Accept-Ranges: bytes,
Access-Control-Allow-Origin: *,
Cache-Control: max-age=300,
Connection: keep-alive,
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox,
Cross-Origin-Resource-Policy: cross-origin,
Strict-Transport-Security: max-age=31536000,
Vary: Authorization|Accept-Encoding|Origin,
Via: 1.1 varnish,
X-Content-Type-Options: nosniff,
X-Frame-Options: deny,
X-XSS-Protection: 1; mode=block
},
ResponseContent:
MIT License
Copyright (c) .NET Foundation and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
]
There a Pause/Resume semantics:
var collection = new ServiceCollection();
collection.AddScoped<MyService>();
var httpBuilder = collection.AddHttpClient<MyService>();
// Adds a AddHttpClient and adds a RecordingHandler using AddHttpMessageHandler
var recording = httpBuilder.AddRecording();
await using var provider = collection.BuildServiceProvider();
var myService = provider.GetRequiredService<MyService>();
// Recording is enabled by default. So Pause to stop recording
recording.Pause();
await myService.MethodThatDoesHttp();
// Resume recording
recording.Resume();
await myService.MethodThatDoesHttp();
await Verify(recording.Sends);
If the AddRecordingHttpClient
helper method does not meet requirements, the RecordingHandler
can be explicitly added:
var collection = new ServiceCollection();
var builder = collection.AddHttpClient("name");
// Change to not recording at startup
var recording = new RecordingHandler(recording: false);
builder.AddHttpMessageHandler(() => recording);
await using var provider = collection.BuildServiceProvider();
var factory = provider.GetRequiredService<IHttpClientFactory>();
var client = factory.CreateClient("name");
await client.GetAsync("https://www.google.com/");
recording.Resume();
await client.GetAsync("https://raw.githubusercontent.com/VerifyTests/Verify/main/license.txt");
await Verify(recording.Sends);
Http Recording allows, when a method is being tested, for any http requests made as part of that method call to be recorded and verified.
Call HttpRecording.StartRecording();
before the method being tested is called.
The perform the verification as usual:
[Fact]
public async Task TestHttpRecording()
{
Recording.Start();
var sizeOfResponse = await MethodThatDoesHttpCalls();
await Verify(
new
{
sizeOfResponse
})
.IgnoreMember("Expires");
}
static async Task<int> MethodThatDoesHttpCalls()
{
using var client = new HttpClient();
var jsonResult = await client.GetStringAsync("https://github.com/VerifyTests/Verify.Http/raw/main/src/global.json");
var ymlResult = await client.GetStringAsync("https://github.com/VerifyTests/Verify.Http/raw/main/src/appveyor.yml");
return jsonResult.Length + ymlResult.Length;
}
The requests/response pairs will be appended to the verified file.
{
target: {
sizeOfResponse: 771
},
httpCall: [
{
Status: Created,
Request: {
Uri: https://github.com/VerifyTests/Verify.Http/raw/main/src/global.json,
Headers: {}
},
Response: {
Status: 302 Found,
Headers: {
Access-Control-Allow-Origin: ,
Cache-Control: no-cache,
Content-Security-Policy: default-src 'none'; base-uri 'self'; child-src github.com/assets-cdn/worker/ github.com/webpack/ github.com/assets/ gist.github.com/assets-cdn/worker/; connect-src 'self' uploads.github.com www.githubstatus.com collector.github.com raw.githubusercontent.com api.github.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com *.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com objects-origin.githubusercontent.com copilot-proxy.githubusercontent.com proxy.individual.githubcopilot.com proxy.business.githubcopilot.com proxy.enterprise.githubcopilot.com *.actions.githubusercontent.com wss://*.actions.githubusercontent.com productionresultssa0.blob.core.windows.net/ productionresultssa1.blob.core.windows.net/ productionresultssa2.blob.core.windows.net/ productionresultssa3.blob.core.windows.net/ productionresultssa4.blob.core.windows.net/ productionresultssa5.blob.core.windows.net/ productionresultssa6.blob.core.windows.net/ productionresultssa7.blob.core.windows.net/ productionresultssa8.blob.core.windows.net/ productionresultssa9.blob.core.windows.net/ productionresultssa10.blob.core.windows.net/ productionresultssa11.blob.core.windows.net/ productionresultssa12.blob.core.windows.net/ productionresultssa13.blob.core.windows.net/ productionresultssa14.blob.core.windows.net/ productionresultssa15.blob.core.windows.net/ productionresultssa16.blob.core.windows.net/ productionresultssa17.blob.core.windows.net/ productionresultssa18.blob.core.windows.net/ productionresultssa19.blob.core.windows.net/ github-production-repository-image-32fea6.s3.amazonaws.com github-production-release-asset-2e65be.s3.amazonaws.com insights.github.com wss://alive.github.com api.githubcopilot.com api.individual.githubcopilot.com api.business.githubcopilot.com api.enterprise.githubcopilot.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com copilot-workspace.githubnext.com objects-origin.githubusercontent.com; frame-ancestors 'none'; frame-src viewscreen.githubusercontent.com notebooks.githubusercontent.com; img-src 'self' data: blob: github.githubassets.com media.githubusercontent.com camo.githubusercontent.com identicons.github.com avatars.githubusercontent.com private-avatars.githubusercontent.com github-cloud.s3.amazonaws.com objects.githubusercontent.com secured-user-images.githubusercontent.com/ user-images.githubusercontent.com/ private-user-images.githubusercontent.com opengraph.githubassets.com github-production-user-asset-6210df.s3.amazonaws.com customer-stories-feed.github.com spotlights-feed.github.com objects-origin.githubusercontent.com *.githubusercontent.com; manifest-src 'self'; media-src github.com user-images.githubusercontent.com/ secured-user-images.githubusercontent.com/ private-user-images.githubusercontent.com github-production-user-asset-6210df.s3.amazonaws.com gist.github.com; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com; upgrade-insecure-requests; worker-src github.com/assets-cdn/worker/ github.com/webpack/ github.com/assets/ gist.github.com/assets-cdn/worker/,
Location: https://raw.githubusercontent.com/VerifyTests/Verify.Http/main/src/global.json,
Referrer-Policy: no-referrer-when-downgrade,
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload,
Vary: X-PJAX,X-PJAX-Container,Turbo-Visit,Turbo-Frame,Accept-Encoding,Accept,X-Requested-With,
X-Content-Type-Options: nosniff,
X-Frame-Options: deny,
X-XSS-Protection: 0
},
ContentHeaders: {
Content-Type: text/html; charset=utf-8
},
ContentString:
}
},
{
Status: Created,
Request: {
Uri: https://raw.githubusercontent.com/VerifyTests/Verify.Http/main/src/global.json,
Headers: {}
},
Response: {
Status: 200 OK,
Headers: {
Accept-Ranges: bytes,
Access-Control-Allow-Origin: *,
Cache-Control: max-age=300,
Connection: keep-alive,
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox,
Cross-Origin-Resource-Policy: cross-origin,
Strict-Transport-Security: max-age=31536000,
Vary: Authorization,Accept-Encoding,Origin,
Via: 1.1 varnish,
X-Content-Type-Options: nosniff,
X-Frame-Options: deny,
X-XSS-Protection: 1; mode=block
},
ContentHeaders: {
Content-Type: text/plain; charset=utf-8
},
ContentString:
{
"sdk": {
"version": "9.0.100",
"allowPrerelease": true,
"rollForward": "latestFeature"
}
}
}
},
{
Status: Created,
Request: {
Uri: https://github.com/VerifyTests/Verify.Http/raw/main/src/appveyor.yml,
Headers: {}
},
Response: {
Status: 302 Found,
Headers: {
Access-Control-Allow-Origin: ,
Cache-Control: no-cache,
Content-Security-Policy: default-src 'none'; base-uri 'self'; child-src github.com/assets-cdn/worker/ github.com/webpack/ github.com/assets/ gist.github.com/assets-cdn/worker/; connect-src 'self' uploads.github.com www.githubstatus.com collector.github.com raw.githubusercontent.com api.github.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com *.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com objects-origin.githubusercontent.com copilot-proxy.githubusercontent.com proxy.individual.githubcopilot.com proxy.business.githubcopilot.com proxy.enterprise.githubcopilot.com *.actions.githubusercontent.com wss://*.actions.githubusercontent.com productionresultssa0.blob.core.windows.net/ productionresultssa1.blob.core.windows.net/ productionresultssa2.blob.core.windows.net/ productionresultssa3.blob.core.windows.net/ productionresultssa4.blob.core.windows.net/ productionresultssa5.blob.core.windows.net/ productionresultssa6.blob.core.windows.net/ productionresultssa7.blob.core.windows.net/ productionresultssa8.blob.core.windows.net/ productionresultssa9.blob.core.windows.net/ productionresultssa10.blob.core.windows.net/ productionresultssa11.blob.core.windows.net/ productionresultssa12.blob.core.windows.net/ productionresultssa13.blob.core.windows.net/ productionresultssa14.blob.core.windows.net/ productionresultssa15.blob.core.windows.net/ productionresultssa16.blob.core.windows.net/ productionresultssa17.blob.core.windows.net/ productionresultssa18.blob.core.windows.net/ productionresultssa19.blob.core.windows.net/ github-production-repository-image-32fea6.s3.amazonaws.com github-production-release-asset-2e65be.s3.amazonaws.com insights.github.com wss://alive.github.com api.githubcopilot.com api.individual.githubcopilot.com api.business.githubcopilot.com api.enterprise.githubcopilot.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com copilot-workspace.githubnext.com objects-origin.githubusercontent.com; frame-ancestors 'none'; frame-src viewscreen.githubusercontent.com notebooks.githubusercontent.com; img-src 'self' data: blob: github.githubassets.com media.githubusercontent.com camo.githubusercontent.com identicons.github.com avatars.githubusercontent.com private-avatars.githubusercontent.com github-cloud.s3.amazonaws.com objects.githubusercontent.com secured-user-images.githubusercontent.com/ user-images.githubusercontent.com/ private-user-images.githubusercontent.com opengraph.githubassets.com github-production-user-asset-6210df.s3.amazonaws.com customer-stories-feed.github.com spotlights-feed.github.com objects-origin.githubusercontent.com *.githubusercontent.com; manifest-src 'self'; media-src github.com user-images.githubusercontent.com/ secured-user-images.githubusercontent.com/ private-user-images.githubusercontent.com github-production-user-asset-6210df.s3.amazonaws.com gist.github.com; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com; upgrade-insecure-requests; worker-src github.com/assets-cdn/worker/ github.com/webpack/ github.com/assets/ gist.github.com/assets-cdn/worker/,
Location: https://raw.githubusercontent.com/VerifyTests/Verify.Http/main/src/appveyor.yml,
Referrer-Policy: no-referrer-when-downgrade,
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload,
Vary: X-PJAX,X-PJAX-Container,Turbo-Visit,Turbo-Frame,Accept-Encoding,Accept,X-Requested-With,
X-Content-Type-Options: nosniff,
X-Frame-Options: deny,
X-XSS-Protection: 0
},
ContentHeaders: {
Content-Type: text/html; charset=utf-8
},
ContentString:
}
},
{
Status: Created,
Request: {
Uri: https://raw.githubusercontent.com/VerifyTests/Verify.Http/main/src/appveyor.yml,
Headers: {}
},
Response: {
Status: 200 OK,
Headers: {
Accept-Ranges: bytes,
Access-Control-Allow-Origin: *,
Cache-Control: max-age=300,
Connection: keep-alive,
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox,
Cross-Origin-Resource-Policy: cross-origin,
Strict-Transport-Security: max-age=31536000,
Vary: Authorization,Accept-Encoding,Origin,
Via: 1.1 varnish,
X-Content-Type-Options: nosniff,
X-Frame-Options: deny,
X-XSS-Protection: 1; mode=block
},
ContentHeaders: {
Content-Type: text/plain; charset=utf-8
},
ContentString:
image: Visual Studio 2022
environment:
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
build_script:
- pwsh: |
Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile "./dotnet-install.ps1"
./dotnet-install.ps1 -JSonFile src/global.json -Architecture x64 -InstallDir 'C:\Program Files\dotnet'
- dotnet build src --configuration Release
- dotnet test src --configuration Release --no-build --no-restore --filter Category!=Integration
test: off
on_failure:
- ps: Get-ChildItem *.received.* -recurse | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }
artifacts:
- path: nugets\*.nupkg
}
}
]
}
The above usage results in the http calls being automatically added snapshot file. Calls can also be explicitly read and recorded using HttpRecording.FinishRecording()
. This enables:
- Filtering what http calls are included in the snapshot.
- Only verifying a subset of information for each http call.
- Performing additional asserts on http calls.
For example:
[Fact]
public async Task TestHttpRecordingExplicit()
{
Recording.Start();
var responseSize = await MethodThatDoesHttpCalls();
var httpCalls = Recording.Stop()
.Select(_ => _.Data)
.OfType<HttpCall>()
.ToList();
// Ensure all calls finished in under 5 seconds
var threshold = TimeSpan.FromSeconds(5);
foreach (var call in httpCalls)
{
Assert.True(call.Duration < threshold);
}
await Verify(
new
{
responseSize,
// Only use the Uri in the snapshot
httpCalls = httpCalls.Select(_ => _.Request.Uri)
});
}
{
responseSize: 771,
httpCalls: [
https://github.com/VerifyTests/Verify.Http/raw/main/src/global.json,
https://raw.githubusercontent.com/VerifyTests/Verify.Http/main/src/global.json,
https://github.com/VerifyTests/Verify.Http/raw/main/src/appveyor.yml,
https://raw.githubusercontent.com/VerifyTests/Verify.Http/main/src/appveyor.yml
]
}
MockHttpClient
allows mocking of http responses and recording of http requests.
The default behavior is to return a HttpResponseMessage
with a status code of 200 OK
.
[Fact]
public async Task DefaultContent()
{
using var client = new MockHttpClient();
var result = await client.GetAsync("https://fake/get");
await Verify(result);
}
{
Version: 1.1,
Status: 200 OK
}
Request-Response pairs can be verified using MockHttpClient.Calls
[Fact]
public async Task RecordedCalls()
{
using var client = new MockHttpClient();
await client.GetAsync("https://fake/get1");
await client.GetAsync("https://fake/get2");
await Verify(client.Calls);
}
[
{
Request: https://fake/get1,
Response: 200 Ok
},
{
Request: https://fake/get2,
Response: 200 Ok
}
]
Always return an explicit StringContent
and media-type:
[Fact]
public async Task ExplicitContent()
{
using var client = new MockHttpClient(
content: """{ "a": "b" }""",
mediaType: "application/json");
var result = await client.GetAsync("https://fake/get");
await Verify(result);
}
{
Status: 200 OK,
Content: {
Headers: {
Content-Type: application/json; charset=utf-8
},
Value: {
a: b
}
}
}
Always return an explicit HttpStatusCode
:
[Fact]
public async Task ExplicitStatusCode()
{
using var client = new MockHttpClient(HttpStatusCode.Ambiguous);
var result = await client.GetAsync("https://fake/get");
await Verify(result);
}
{
Version: 1.1,
Status: 300 Multiple Choices
}
Alwars return an explicit HttpResponseMessage
:
[Fact]
public async Task ExplicitResponse()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello")
};
using var client = new MockHttpClient(response);
var result = await client.GetAsync("https://fake/get");
await Verify(result);
}
{
Status: 200 OK,
Content: {
Headers: {
Content-Type: text/plain; charset=utf-8
},
Value: Hello
}
}
Use custom code to create a HttpResponseMessage
base on a HttpRequestMessage
:
[Fact]
public async Task ResponseBuilder()
{
using var client = new MockHttpClient(
request =>
{
var content = $"Hello to {request.RequestUri}";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(content),
};
return response;
});
var result1 = await client.GetAsync("https://fake/get1");
var result2 = await client.GetAsync("https://fake/get2");
await Verify(new
{
result1,
result2
});
}
{
result1: {
Status: 200 OK,
Content: {
Headers: {
Content-Type: text/plain; charset=utf-8
},
Value: Hello to https://fake/get1
}
},
result2: {
Status: 200 OK,
Content: {
Headers: {
Content-Type: text/plain; charset=utf-8
},
Value: Hello to https://fake/get2
}
}
}
Use a sequence of HttpResponseMessage
to return a sequence of requests:
[Fact]
public async Task EnumerableResponses()
{
using var client = new MockHttpClient(
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello")
},
new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("World")
});
var result1 = await client.GetAsync("https://fake/get1");
var result2 = await client.GetAsync("https://fake/get2");
await Verify(new
{
result1,
result2
});
}
{
result1: {
Status: 200 OK,
Content: {
Headers: {
Content-Type: text/plain; charset=utf-8
},
Value: Hello
}
},
result2: {
Status: 200 OK,
Content: {
Headers: {
Content-Type: text/plain; charset=utf-8
},
Value: World
}
}
}
Spider designed by marialuisa iborra from The Noun Project.