ASP.NET MVC:单元测试会话变量不会改变

时间:2014-01-31 21:28:09

标签: asp.net-mvc unit-testing session moq

我正在尝试对我的控制器的Logout操作进行单元测试。我的控制器重新接收一个处理会话变量的接口:

public HomeController(IUnitOfWork unitOfWork, ISecurityService security = null) 
{
    _unitOfWork = unitOfWork;   

    if (security != null)
    {
        _securityService = security;
    }
    else
    {
        _userService = new UserService(_unitOfWork)
        _securityService = new SecurityService(_userService);    
    }
}

使用Moq,我创建了一个HttpSessionStateBase对象 我用它来在我的单元测试类中创建一个SecurityService对象:

var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupGet(s => s["UserID"]).Returns("1");
HttpSessionStateBase session = mockSession.Object;
ISecurityService _securityService = new SecurityService(_userService, session);

My SecurityService

public class SecurityService : ISecurityService 
{
    private readonly IUsuarioService _userService ;
    private readonly HttpSessionStateBase _session;

    public int UserID
    {
        get { return Convert.ToInt32(_session["UserID"]); }
        set { _session["UserID"] = value; }
    }

    public SecurityService(IUserService service, HttpSessionStateBase session = null)
    {
        _userService = service;
        _session = session ?? new HttpSessionStateWrapper(HttpContext.Current.Session);
    }

    public void Logout()
    {
        // I'm trying to delete this variable, but I can't
        _session["UserID"] = 0;
        _session.Clear();
        _session.Abandon();
    }
}

最后,我的测试方法

[TestMethod]
    public void Should_delete_session_variable_from_the_user()
    {
        controller.Logout();

        // It's allways 1
        Assert.IsTrue(Convert.ToInt32(session["UserID"]) == 0);
    }

当我调试这段代码时,我可以看到会话变量没有变化它的值。但是,如果我打开“快速监视”窗口并执行_session["UserID"] = 0;,则其值会发生变化。

我无法理解为什么。这是我第一次看到变量在调试时没有变化它。

1 个答案:

答案 0 :(得分:0)

最后我发现,解决方法是添加SetupSet方法 这是最终的代码:

int sessionValue = 0;
var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupSet(s => s["UserId"] = It.IsAny<int>())
    .Callback((string name, object val) => sessionValue = (int) val);
mockSession.SetupGet(s => s["UserId"]).Returns(() => sessionValue);