【问题标题】:Object reference not set to an instance of an object at ASP.NET MVC Session on Unit Testing using Fake it Easy在使用 Fake it Easy 进行单元测试的 ASP.NET MVC 会话中,对象引用未设置为对象的实例
【发布时间】:2022-09-29 21:27:35
【问题描述】:

我有一个带有控制器的 ASP.NET MVC 4 项目,该控制器调用外部 WCF 以在 VerifyAccount 方法上验证用户登录。这个外部 WCF 将一个 AuthModelUserVerification 类返回给控制器并创建一个包含用户 ID 的 Session

[HttpPost]
public ActionResult VerifyAccount(string username, string password) {

    AuthModelUserVerification result = lms_client.VerifyAccount(username, password);

    if (!result.isAuthenticated)
        return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);

    Session[\"SID\"] = result.userid;

    return new HttpStatusCodeResult(HttpStatusCode.OK);
}

下面是来自 WCF 的 AuthModelUserVerification 的结构:

public class AuthModel
{
    public class UserVerification {
        public int? userid { get; set; }
        public bool isAuthenticated { get; set; }

        public UserVerification()
        {
            userid = null;
            isAuthenticated = false;
        }
    }
}

我正在尝试对VerifyAccount 方法进行单元测试,以测试在某些条件下返回给浏览器的状态代码。我在用MSTest (.NET)假装很容易模拟框架。问题在于在Session[\"SID\"] 上设置值

Session[\"SID\"] = result.userid;

调试测试时,我在此行收到以下错误:

你调用的对象是空的

在调试测试时,每次我将鼠标悬停在Session[\"SID\"] 上时,它都会显示为空,但result.userid 显示它的值为1因为我通过调用我制作的模拟服务将值传递给它。请在此处查看我的测试的实现:

private readonly AuthController _controller_Auth;
private readonly ILMS_Service _lms_service;

public Auth_UnitTest() {
    _lms_service = A.Fake<ILMS_Service>();
    _controller_Auth = new AuthController(_lms_service);
}

[TestMethod]
public void VerifyAccount_Success()
{
    //Arrange
    string username = \"admin\";
    string password = \"sampleP@sswoRd\";
    int userID = 1;

    int expected_response_code = 200;
    var session = A.Fake<HttpSessionStateBase>();

    A.CallTo(() => session[\"SID\"]).Returns(userID);

    A.CallTo(() => _lms_service.VerifyAccount(username, password))
        .Returns(new AuthModelUserVerification
        {
            userid = userID,
            isAuthenticated = true
        });

    //Act
    var result = _controller_Auth.VerifyAccount(username, password) as HttpStatusCodeResult;

    //Assert
    Assert.AreEqual(expected_response_code, result.StatusCode);
}

该模拟正在工作,因为当我调试它时,isAuthenticated 的值是 true。是 Session 不起作用。即使制作一个假的HttpSessionStateBase 也不能解决问题。我是单元测试的新手,我仍在探索事物,任何帮助将不胜感激。谢谢!

    标签: c# asp.net-mvc unit-testing mstest fakeiteasy


    【解决方案1】:

    我看到 session 正在创建和配置,但它与 _controller_Auth 之间没有任何联系。我怀疑后者正在使用未初始化的 Session 属性。伪造的session 对象需要提供给被测系统。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2014-10-15
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多