使用自定义输入模型对 ASP.NET Mvc 控制器进行单元测试 (xUnit)?

发布于 2024-09-01 17:05:41 字数 1505 浏览 10 评论 0原文

我很难找到关于我期望的非常简单的场景的信息。我正在尝试对 ASP.NET Mvc 2 控制器上的操作进行单元测试,该控制器使用带有 DataAnnotions 的自定义输入模型。我的测试框架是xUnit,如标题中提到的。

这是我的自定义输入模型

public class EnterPasswordInputModel
{
    [Required(ErrorMessage = "")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Password is a required field.")]
    public string Password { get; set; }
}

这是我的控制器(为这个示例取出了一些逻辑来简化。):

[HttpPost]
public ActionResult EnterPassword(EnterPasswordInputModel enterPasswordInput)
{
    if (!ModelState.IsValid)
        return View();

    // do some logic to validate input
    // if valid - next View on successful validation
        return View("NextViewName");
    // else - add and display error on current view
        return View();
}

这是我的xUnit Fact(也简化了):

[Fact]
public void EnterPassword_WithValidInput_ReturnsNextView()
{
    // Arrange
    var controller = CreateLoginController(userService.Object);

    // Act
    var result = controller.EnterPassword(
        new EnterPasswordInputModel
            {
                Username = username, Password = password
            }) as ViewResult;

    // Assert
    Assert.Equal("NextViewName", result.ViewName);
}

当我运行测试时,在尝试检索控制器结果(操作部分)时,我的测试事实出现以下错误:

System.NullReferenceException: Object reference not set to an instance of an object.

提前感谢您提供的任何帮助!

I'm having a hard time finding information on what I expect to be a pretty straightforward scenario. I'm trying to unit test an Action on my ASP.NET Mvc 2 Controller that utilizes a custom input model w/ DataAnnotions. My testing framework is xUnit, as mentioned in the title.

Here is my custom Input Model:

public class EnterPasswordInputModel
{
    [Required(ErrorMessage = "")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Password is a required field.")]
    public string Password { get; set; }
}

And here is my Controller (took out some logic to simplify for this ex.):

[HttpPost]
public ActionResult EnterPassword(EnterPasswordInputModel enterPasswordInput)
{
    if (!ModelState.IsValid)
        return View();

    // do some logic to validate input
    // if valid - next View on successful validation
        return View("NextViewName");
    // else - add and display error on current view
        return View();
}

And here is my xUnit Fact (also simplified):

[Fact]
public void EnterPassword_WithValidInput_ReturnsNextView()
{
    // Arrange
    var controller = CreateLoginController(userService.Object);

    // Act
    var result = controller.EnterPassword(
        new EnterPasswordInputModel
            {
                Username = username, Password = password
            }) as ViewResult;

    // Assert
    Assert.Equal("NextViewName", result.ViewName);
}

When I run my test I get the following error on my test fact when trying to retrieve the controller result (Act section):

System.NullReferenceException: Object reference not set to an instance of an object.

Thanks in advance for any help you can offer!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦醒灬来后我 2024-09-08 17:05:41

我想我正在寻找解决方案。这是我对控制器所做的更改:

原始

if (!ModelState.IsValid)
    return View();

更新

if (!TryUpdateModel(loginInput))
            return View();

在我的测试过程中似乎没有发生模型绑定。除非发生 POST,否则模型绑定似乎不会发生。通过强制尝试的模型绑定,我能够让测试通过。

注意:我的操作中还存在一个错误,导致我在尝试找出模型未经过验证的原因时导致原始空引用。

参考:
http:// bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

I think I'm on the track to a solution though. Here is the change I made to my controller:

Original

if (!ModelState.IsValid)
    return View();

Updated

if (!TryUpdateModel(loginInput))
            return View();

It seems that model binding was not occurring during my test. It appears that the model binding does not take place unless a POST occurs. By forcing the attempted model binding I was able to get the test to pass.

Note: There was also an error in my action that was causing my original null reference that I caused while trying to figure out why my model wasn't being validated.

Reference:
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

过气美图社 2024-09-08 17:05:41

您正在取消引用控制器操作内的空实例。可能在您拿出来“简化”问题的代码中。查看测试结果中的调用堆栈以了解内容。您可能需要模拟一些东西来进行测试。

You're dereferencing a null instance inside your controller action. Probably in the code you took out to "simplify" the question. Look at the call stack in the test results to figure out what. You may need to mock something for the test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文