如何断言在C#中发出的请求中发送了特定的请求头部分?

huangapple go评论103阅读模式
英文:

How to assert that a specific request header is sent in a outgoing request C#

问题

I want to test a scenario

As part of the API logic, a header will be sent as part of an outgoing HTTP call.
like

  1. public class MyClass {
  2. public NewResponse MySpecificHeaderApi(HttpRequestMessage request) {
  3. if (OnSomeCondition()) {
  4. // I want to test whether this header added or not
  5. request.Headers.TryAddWithoutValidation("X-Specific-Header", "some values");
  6. }
  7. var httpClient = httpClientFactory.CreateHttpClient("Some name");
  8. var response = httpClient.SendAsync(request).GetAwaiter().GetResult();
  9. // Here we lost X-Specific-Header, as we took only the status code
  10. // from the original response.
  11. return NewResponse(response.StatusCode);
  12. }
  13. }

So now if I want to test the API MySpecificHeaderApi.

// Arrange
var request = new HttpRequestMessage(Get, "some URI");

// Act
var response = new MyClass().MySpecificHeaderApi(request);

// Assert
response.Headers.should().Contain("X-Specific-Header"); // Will fail because the actual request details are missed out from the original response in MyClass.MySpecificHeaderApi()

英文:

I want to test a scenario

As part of the API logic a header will be sent as part of an outgoing http call.
like

  1. public class MyClass{
  2. public NewResponse MySepcificHeaderApi(HttpRequestMessage request) {
  3. if( OnSomeCondition()){
  4. // i want to test whether this header added or not
  5. request.Headers.TryAddWithoutValidation("X-Specific-Header", "some values");
  6. }
  7. var httpClient = httpClientFactory.CreateHttpClient("Some name");
  8. var response = httpClient.SendAsync(request).GetAwaiter().GetResult();
  9. // here we lost X-Specific-Header, as we taken only status code
  10. // from the original response.
  11. return NewResponse(response.StatusCode);
  12. }
  13. }

So now if I want to test the API MySepcificHeaderApi .

  1. // arrange
  2. var request = new HttpRequestMessage(Get, "some uri");
  3. // act
  4. var response = new MyClass().MySepcificHeaderApi(request);
  5. //assert
  6. response.Headers.should().Contain("X-Spcific-Header"); // will fail, because the actual requet details are missed out from original response in MyClass.MySepcificHeaderApi()

答案1

得分: 1

为了解决这个问题,我们可以使用HttpRequestInterceptionBuilderWebApplicationFactory<TEntryPoint>来解决该问题。

  1. // 安排
  2. CustomWebApplicationFactory<Program>? webApplicationFactory = new CustomWebApplicationFactory<Program>();
  3. HttpClientInterceptorOptions? interceptorOptions = webApplicationFactory.InterceptorOptions;
  4. interceptorOptions.BeginScope();
  5. var httpClient = webApplicationFactory.CreateClient();
  6. var headers = new Dictionary<string, string>();
  7. new HttpRequestInterceptionBuilder()
  8. .Requests()
  9. .WithInterceptionCallback(i =>
  10. {
  11. foreach (var httpRequestHeader in i.Headers)
  12. {
  13. headers.Add(httpRequestHeader.Key,
  14. httpRequestHeader.Value.FirstOrDefault());
  15. }
  16. })
  17. .ForPost()
  18. .ForHttp()
  19. .ForHost("localhost")
  20. .ForPath("some uri")
  21. .ForRequestHeader("X-Specific-Header", "some values")
  22. .Responds()
  23. .WithStatus(HttpStatusCode.OK)
  24. .RegisterWith(interceptorOptions);
  25. // 上面的HttpRequestInterceptionBuilder将返回OK状态,只有当请求包含"X-Specific-Header"时,我们才会断言头部已添加。
  26. var request = new HttpRequestMessage(Get, "http://localhost/some uri");
  27. // 执行
  28. var response = new MyClass().MySepcificHeaderApi(request);
  29. // 断言
  30. reponse.StatusCode.Should().Be(Ok);
  31. headers.Should().ContainKey("X-Specific-Header");
  32. headers["X-Specific-Header"].Should().Be("some values");

注意:代码部分未翻译,仅提供了翻译的注释和字符串内容。

英文:

To solve this we can use HttpRequestInterceptionBuilder and WebApplicationFactory<TEntryPoint> to solve the issue.

  1. // arrange
  2. CustomWebApplicationFactory<Program>? webApplicationFactory = new CustomWebApplicationFactory<Program>();
  3. HttpClientInterceptorOptions? interceptorOptions = webApplicationFactory.InterceptorOptions;
  4. interceptorOptions.BeginScope();
  5. var httpClient = webApplicationFactory.CreateClient();
  6. var headers = new Dictionary<string, string>();
  7. new HttpRequestInterceptionBuilder()
  8. .Requests()
  9. .WithInterceptionCallback(i =>
  10. {
  11. foreach (var httpRequestHeader in i.Headers)
  12. {
  13. headers.Add(httpRequestHeader.Key,
  14. httpRequestHeader.Value.FirstOrDefault());
  15. }
  16. })
  17. .ForPost()
  18. .ForHttp()
  19. .ForHost("localhost")
  20. .ForPath($"some uri")
  21. .ForRequestHeader("X-Specific-Header", "some values")
  22. .Responds()
  23. .WithStatus(HttpStatusCode.OK)
  24. .RegisterWith(interceptorOptions);
  25. // the above HttpRequestInterceptionBuilder will return OK status, only is the request contains the "X-Specific-Header, that way we are asserting the header is added.
  26. var request = new HttpRequestMessage(Get, "http://localhost/some uri");
  27. // act
  28. var response = new MyClass().MySepcificHeaderApi(request);
  29. //assert
  30. reponse.StatusCode.Should().Be(Ok);
  31. headers.Should().ContainKey("X-Specific-Header");
  32. headers["X-Specific-Header"].Should().Be("some values");

huangapple
  • 本文由 发表于 2023年7月17日 19:14:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定