Skip to content

Extends Verify to allow verification of web bits.

License

Notifications You must be signed in to change notification settings

VerifyTests/Verify.Http

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Verify.Http

Discussions Build status NuGet Status

Extends Verify to allow verification of Http bits.

See Milestones for release notes.

NuGet package

https://nuget.org/packages/Verify.Http/

Initialize

Call VerifierSettings.InitializePlugins() in a [ModuleInitializer].

public static class ModuleInitializer
{
    [ModuleInitializer]
    public static void Initialize() =>
        VerifierSettings.InitializePlugins();
}

snippet source | anchor

Or, if order of plugins is important, use VerifyHttp.Initialize() in a [ModuleInitializer].

Enable Recording

Enable at any point in a test using VerifyTests.Recording.Start().

Converters

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);
}

snippet source | anchor

Resulting verified file

{
  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.

  }
}

snippet source | anchor

Ignoring Headers

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");
}

snippet source | anchor

HttpClient recording via Service

For code that does web calls via HttpClient, these calls can be recorded and verified.

Service that does http

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");
}

snippet source | anchor

Add to IHttpClientBuilder

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);

snippet source | anchor

Add globally

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);

snippet source | anchor

Resulting verified file

[
  {
    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.

  }
]

snippet source | anchor

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);

snippet source | anchor

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);

snippet source | anchor

Http Recording via listener

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.

Usage

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;
}

snippet source | anchor

Resulting verified file

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
      }
    }
  ]
}

snippet source | anchor

Explicit Usage

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)
        });
}

snippet source | anchor

Resulting verified file

{
  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
  ]
}

snippet source | anchor

Mocking

MockHttpClient allows mocking of http responses and recording of http requests.

Default Response

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);
}

snippet source | anchor

Resulting verified file

{
  Version: 1.1,
  Status: 200 OK
}

snippet source | anchor

Verifying Calls

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);
}

snippet source | anchor

Resulting verified file

[
  {
    Request: https://fake/get1,
    Response: 200 Ok
  },
  {
    Request: https://fake/get2,
    Response: 200 Ok
  }
]

snippet source | anchor

Explicit Content Response

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);
}

snippet source | anchor

Resulting verified file

{
  Status: 200 OK,
  Content: {
    Headers: {
      Content-Type: application/json; charset=utf-8
    },
    Value: {
      a: b
    }
  }
}

snippet source | anchor

Explicit HttpStatusCode Response

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);
}

snippet source | anchor

Resulting verified file

{
  Version: 1.1,
  Status: 300 Multiple Choices
}

snippet source | anchor

Explicit HttpResponseMessage

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);
}

snippet source | anchor

Resulting verified file

{
  Status: 200 OK,
  Content: {
    Headers: {
      Content-Type: text/plain; charset=utf-8
    },
    Value: Hello
  }
}

snippet source | anchor

HttpResponseMessage builder

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
    });
}

snippet source | anchor

Resulting verified file

{
  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
    }
  }
}

snippet source | anchor

Enumeration of HttpResponseMessage

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
    });
}

snippet source | anchor

Resulting verified file

{
  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
    }
  }
}

snippet source | anchor

Icon

Spider designed by marialuisa iborra from The Noun Project.

About

Extends Verify to allow verification of web bits.

Resources

License

Code of conduct

Stars

Watchers

Forks

Sponsor this project

 

Languages