David Klempfner
David Klempfner

Reputation: 9870

Model Validation Not Working In Unit Test

I have the following unit test:

[TestMethod]
public void GivenInvalidUrlExpectInvalidModelState()
{
    //Arrange
    HomeController homeController = new HomeController();
    InputFields inputFields = new InputFields { Url = "google.com/", KeyWords = "some key words" };

    //Act
    ViewResult actionResult = homeController.GetResults(inputFields);

    //Assert
    Assert.IsFalse(actionResult.ViewData.ModelState.IsValid);
}

And the following model:

public class InputFields
{
    [Url]
    [Required(ErrorMessage="Please provide a URL")]
    public string Url { get; set; }
    [Required(ErrorMessage="Please provide key words")]
    public string KeyWords { get; set; }
}

When I hit the controller from the UI with an invalid URL (without protocol) such as google.com/ the ModelState is false as expected.

However in the unit test, the ModelState is true.

Why is the model not being validated in the unit test?

Upvotes: 1

Views: 1411

Answers (1)

Nkosi
Nkosi

Reputation: 247123

Those validation attributes are evaluated by the asp.net mvc framework during run time through the pipeline. When running a unit test there is no pipeline so certain expectations wont apply.

You would have to manipulate the state yourself

[TestMethod]
public void GivenInvalidUrlExpectInvalidModelState() {
    //Arrange
    var homeController = new HomeController();
    //manually adding error that would cause `ModelState.IsValid` to be false
    homeController.ModelState.AddModelError("Url", "invalid data");
    var inputFields = new InputFields { Url = "google.com/", KeyWords = "some key words" };

    //Act
    ViewResult actionResult = homeController.GetResults(inputFields);

    //Assert
    Assert.IsFalse(actionResult.ViewData.ModelState.IsValid);
}

In order to test the model state within the pipeline you would probably need to run an end to end integration test where an HTTP request is made to the controller

Upvotes: 4

Related Questions