Skip to content

Instantly share code, notes, and snippets.

@uzbekdev1
Forked from johnnyreilly/CarController.cs
Created March 3, 2021 09:12
Show Gist options
  • Save uzbekdev1/94f9dbc83dcdcf0ad2100a5962cf1d81 to your computer and use it in GitHub Desktop.
Save uzbekdev1/94f9dbc83dcdcf0ad2100a5962cf1d81 to your computer and use it in GitHub Desktop.
Unit testing ModelState using Moq
using System.Web.Mvc;
namespace MyApp
{
public class CarController : Controller
{
//...
public ActionResult Edit(CarModel model)
{
if (ModelState.IsValid) {
//Save the model
return View("Details", model);
}
return View(model);
}
//...
}
}
using System;
using System.ComponentModel.DataAnnotations;
namespace MyNamespace.Model
{
public class CarModel
{
[Required,
Display(Name = "Purchased"),
DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime Purchased { get; set; }
[Required,
Display(Name = "Colour")]
public string Colour{ get; set; }
}
}
using System.Web.Mvc;
using Moq;
namespace UnitTests.TestUtilities
{
/// <summary>
/// Instance of a controller for testing things that use controller methods i.e. controller.TryValidateModel(model)
/// </summary>
public class ModelStateTestController : Controller
{
public ModelStateTestController()
{
ControllerContext = (new Mock<ControllerContext>()).Object;
}
public bool TestTryValidateModel(object model)
{
return TryValidateModel(model);
}
}
}
[TestMethod]
public void Unit_Test_CarModel_ModelState_validations_are_thrown()
{
// Arrange
var controller = new ModelStateTestController();
var car = new CarModel
{
Puchased = null, //This is a required property and so this value is invalid
Colour = null //This is a required property and so this value is invalid
};
// Act
var result = controller.TestTryValidateModel(company);
// Assert
Assert.IsFalse(result);
var modelState = controller.ModelState;
Assert.AreEqual(2, modelState.Keys.Count);
Assert.IsTrue(modelState.Keys.Contains("Purchased"));
Assert.IsTrue(modelState["Purchased"].Errors.Count == 1);
Assert.AreEqual("The Purchased field is required.", modelState["Purchased"].Errors[0].ErrorMessage);
Assert.IsTrue(modelState.Keys.Contains("Colour"));
Assert.IsTrue(modelState["Colour"].Errors.Count == 1);
Assert.AreEqual("The Colour field is required.", modelState["Colour"].Errors[0].ErrorMessage);
}
var car = new CarModel
{
Puchased = null, //This is a required property and so this value is invalid
Colour = null //This is a required property and so this value is invalid
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment