gpt4 book ai didi

c# - 单元测试 Web Api Controller 假 ApiController。具有自定义身份的用户不起作用

转载 作者:行者123 更新时间:2023-11-30 12:23:41 25 4
gpt4 key购买 nike

我目前正在使用 Web API v5.2.2,并且正在为其中一个 Controller 编写单元测试代码。我遇到的问题发生在 ApiController.User 部分。

我为用户实现了 IIdentity 接口(interface)的自定义身份:

public class CustomIdentity : IIdentity
{
//Constructor and methods
}

CustomIdentity 是在正常使用的 HttpRequest 中设置的。但由于我只是在单元测试中测试查询功能,所以我只是调用了 Controller 及其方法,而不是发送请求。

因此,我必须将用户身份插入到线程中,我尝试了以下方法:

var controller = new AccountsController(new AccountUserContext());

第一次尝试:

controller.User = new ClaimsPrincipal(new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray()));

第二次尝试:

IPrincipal principal = null;

principal = new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray());

Thread.CurrentPrincipal = principal;

if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}

但是,我在两次尝试中都遇到了这个错误:

Object reference not set to an instance of an object.

而且我发现用户标识在线程中仍然为空。

有人试过这个方法吗?谢谢你的建议!

最佳答案

你说

The CustomIdentity was set in the HttpRequest in normal usage.

您是否在组装测试时将请求附加到 Controller 。

检查这里的例子

Unit Testing Controllers in ASP.NET Web API 2

[TestMethod]
public void QueryAccountControllerTest()
{
// Arrange
var user = "[Username Here]"
var controller = new AccountsController(new AccountUserContext());
//Set a fake request. If your controller creates responses you will need tis
controller.Request = new HttpRequestMessage {
RequestUri = new Uri("http://localhost/api/accounts")
};
controller.Configuration = new HttpConfiguration();
controller.User = new ClaimsPrincipal(new CustomIdentity(user));

// Act
... call action

// Assert
... assert result
}

关于c# - 单元测试 Web Api Controller 假 ApiController。具有自定义身份的用户不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com