Unit Testing (xUnit) an ASP.NET Mvc Controller with a custom input model?

Posted by Danny Douglass on Stack Overflow See other posts from Stack Overflow or by Danny Douglass
Published on 2010-05-14T13:14:10Z Indexed on 2010/05/14 13:24 UTC
Read the original article Hit count: 331

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!

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about xunit.net