Skip to content

Instantly share code, notes, and snippets.

@jayhjkwon
Created January 20, 2012 05:08
Show Gist options
  • Save jayhjkwon/1645402 to your computer and use it in GitHub Desktop.
Save jayhjkwon/1645402 to your computer and use it in GitHub Desktop.
Test with invalid model
[HttpPost]
public ActionResult Write(PostInputViewModel input)
{
//bool val = TryValidateModel(input);
if (!ModelState.IsValid)
return View("Write", input);
var post = new Post
{
Title = input.Title,
ContentWithHtml = input.ContentWithHtml,
DateCreated = DateTime.Now,
DateModified = DateTime.MaxValue
};
dbContext.Posts.Add(post);
dbContext.SaveChanges();
return RedirectToAction("Index", "Home");
}
[TestMethod]
public void write_should_validate_model()
{
var input = new PostInputViewModel();
input.Title = null;
input.ContentWithHtml = null;
// #1 test-validation
//var actionResult = controller.Write(input) as ViewResult;
//Assert.IsFalse(actionResult.ViewData.ModelState.IsValid);
// #2 test-data input failure and view result when model is invalid
controller.ModelState.AddModelError("InvalidModel", "Title and Content are empty");
var actionResult = controller.Write(input) as ViewResult;
Assert.AreEqual("Write", actionResult.ViewName);
Assert.AreEqual(input, actionResult.Model);
Assert.AreEqual(0, context.Posts.Count());
}
public class PostInputViewModel
{
[Required]
[MinLength(1)]
[MaxLength(125)]
public string Title { get; set; }
[Required]
[AllowHtml]
[Display(Name="Content")]
public string ContentWithHtml { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment