【问题标题】:How to pass header value in WebAPI unit test如何在 WebAPI 单元测试中传递标头值
【发布时间】:2017-08-13 01:52:40
【问题描述】:

在 API Controller 中,它获取 HttpContextRequest 标头以获取访问令牌。当我使用 UnitTest 时,我将如何将 access_token 值传递给控制器​​操作。请帮忙。

var _access_token = HttpContext.Current.Request.Headers["access_token"];

【问题讨论】:

  • 使用“授权”http 标头。看到这个stackoverflow.com/questions/16526211/…
  • 提供minimal reproducible example,可用于重现问题以及所需行为。您没有提供足够的信息让我们能够有效地帮助您。此外,您的 Web api 代码似乎与 HttpContext 紧密耦合,这使得单独进行单元测试非常困难。

标签: c# unit-testing asp.net-web-api http-headers


【解决方案1】:

你可以这样写,

//Arrange
var client = new HttpClient { BaseAddress = new Uri("http://localhost:55442/") 
                            };
client.DefaultRequestHeaders.Add("access_token", "YWtoaWw6YWtoaWw=");
Employee emp = new Employee {
            Id=1,
            name = "Test Name",
            salary = "2000"
        };
//Act
var _response = 
client.PostAsJsonAsync(client.BaseAddress +"/"+ "myController"+ "/"+ 
                       "methodName",emp).Result;

//Assert
Assert.IsTrue(true);

干杯...

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多