gpt4 book ai didi

c# - 如何模拟 HttpContext.User

转载 作者:太空狗 更新时间:2023-10-29 21:21:27 24 4
gpt4 key购买 nike

我正在处理一个 Asp.net MVC 5 项目,我正在尝试设置一个模拟以在 Controller 中返回一个自定义主体。我已经搜索并尝试了建议的不同方法,但没有一个有效。

我有一个 BaseController,我的所有 Controller 都继承自它。 BaseController 有一个 User 属性,它在 getter 中返回 HttpContext.User。 HttpContext.user 在项目内调用时返回一个值,但在从单元测试项目调用时返回 null。

基础 Controller

public class BaseController : Controller
{
protected virtual new CustomPrincipal User
{
get { return HttpContext.User as CustomPrincipal; } ***<== Line with issue***
}
}

自定义主体

public class CustomPrincipal : IPrincipal, ICustomPrincipal
{
public IIdentity Identity { get; private set; }

public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsStoreUser { get; set; }

public CustomPrincipal(string username)
{
this.Identity = new GenericIdentity(username);
}
}

Controller

public class DocumentsController : BaseController
{
public ViewResult ViewDocuments()
{
var userType = User.IsStoreUser ? UserType.StoreUser : UserType.Corporate; ***<== User is null when calling from a unit test.***
}
}

测试用例

[Test]
public void ViewDocuments_WhenCalled_ShouldReturnViewModel()
{
// Arrange
var principal = new CustomPrincipal("2038786");
principal.UserId = "2038786";
principal.FirstName = "Test";
principal.LastName = "User";
principal.IsStoreUser = true;

var _mockController = new Mock<DocumentsController>(new UnitOfWork(_context)) { CallBase = true };
_mockController.Setup(u => u.User).Returns(principal); ***<== Error - "Invalid setup on a non-virtual (overridable in VB) member: u => u.User"***

// Act
var result = _controller.ViewDocuments();
}

我正在使用 nUnit 和 Moq 来创建模拟对象,但我不确定我做错了什么。我需要在 DocumentControl 中模拟 User.IsStore 的返回,以在我在测试中创建的自定义主体对象中返回 IsStore 的值。

最佳答案

制作一个模拟的http上下文

private class MockHttpContext : HttpContextBase {
private readonly IPrincipal user;

public MockHttpContext(IPrincipal principal) {
this.user = principal;
}

public override IPrincipal User {
get {
return user;
}
set {
base.User = value;
}
}
}

相应地安排测试。

[Test]
public void ViewDocuments_WhenCalled_ShouldReturnViewModel() {
// Arrange
var principal = new CustomPrincipal("2038786");
principal.UserId = "2038786";
principal.FirstName = "Test";
principal.LastName = "User";
principal.IsStoreUser = true;

var mockUoW = new Mock<IUnitOfWork>();
//...setup UoW dependency if needed
var controller = new DocumentsController(mockUoW.Object);
controller.ControllerContext = new ControllerContext {
Controller = controller,
HttpContext = new MockHttpContext(principal)
};

// Act
var result = controller.ViewDocuments();

//Assert
//...assertions
}

不要模拟被测系统。模拟它的依赖关系。

关于c# - 如何模拟 HttpContext.User,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40230776/

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