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

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

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

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

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

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

So now if I want to test the API MySepcificHeaderApi .

// arrange
var request = new HttpRequestMessage(Get, "some uri");

// act
var response = new MyClass().MySepcificHeaderApi(request);

//assert
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>来解决该问题。

// 安排
CustomWebApplicationFactory<Program>? webApplicationFactory = new CustomWebApplicationFactory<Program>();
HttpClientInterceptorOptions? interceptorOptions = webApplicationFactory.InterceptorOptions;
interceptorOptions.BeginScope();
var httpClient = webApplicationFactory.CreateClient();
var headers = new Dictionary<string, string>();
new HttpRequestInterceptionBuilder()
    .Requests()
    .WithInterceptionCallback(i =>
    {
        foreach (var httpRequestHeader in i.Headers)
        {
            headers.Add(httpRequestHeader.Key,
                httpRequestHeader.Value.FirstOrDefault());
        }
    })
    .ForPost()
    .ForHttp()
    .ForHost("localhost")
    .ForPath("some uri")
    .ForRequestHeader("X-Specific-Header", "some values")
    .Responds()
    .WithStatus(HttpStatusCode.OK)
    .RegisterWith(interceptorOptions);
// 上面的HttpRequestInterceptionBuilder将返回OK状态,只有当请求包含"X-Specific-Header"时,我们才会断言头部已添加。

var request = new HttpRequestMessage(Get, "http://localhost/some uri");

// 执行
var response = new MyClass().MySepcificHeaderApi(request);

// 断言
reponse.StatusCode.Should().Be(Ok);
headers.Should().ContainKey("X-Specific-Header");
headers["X-Specific-Header"].Should().Be("some values");

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

英文:

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

// arrange
CustomWebApplicationFactory<Program>? webApplicationFactory = new CustomWebApplicationFactory<Program>();
HttpClientInterceptorOptions? interceptorOptions = webApplicationFactory.InterceptorOptions;
interceptorOptions.BeginScope();
var httpClient = webApplicationFactory.CreateClient();
var headers = new Dictionary<string, string>();
new HttpRequestInterceptionBuilder()
	.Requests()
	.WithInterceptionCallback(i =>
	{
		foreach (var httpRequestHeader in i.Headers)
		{
			headers.Add(httpRequestHeader.Key,
				httpRequestHeader.Value.FirstOrDefault());
		}
	})
	.ForPost()
	.ForHttp()
	.ForHost("localhost")
	.ForPath($"some uri")
	.ForRequestHeader("X-Specific-Header", "some values")
	.Responds()
	.WithStatus(HttpStatusCode.OK)
	.RegisterWith(interceptorOptions);
// 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.

var request = new HttpRequestMessage(Get, "http://localhost/some uri");

// act
var response = new MyClass().MySepcificHeaderApi(request);

//assert
reponse.StatusCode.Should().Be(Ok);
headers.Should().ContainKey("X-Specific-Header");
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:

确定