Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to unit test some AddModelError results in ASP.NET MVC?

I've got a controller method which returns a RedirectToActionResult (success!) or a ViewResult (failed with error messages).

If the business logic fails, i add the error messages to the AddModelError property.

Is there any way i can test this in my MS Unit tests? I also have Moq, if that helps too. (i don't believe Moq is required for this scenario though) .. I'm not using anything from the Request object.

like image 307
Pure.Krome Avatar asked Apr 06 '09 07:04

Pure.Krome


People also ask

Is it possible to unit test an MVC application without running the controllers in an ASP NET process?

Answer: In an MVC application, all the features are based on interface. So, it is easy to unit test a MVC application. And it is to note that, in MVC application there is no need of running the controllers for unit testing.

Is it possible to unit test Web API?

You can either create a unit test project when creating your application or add a unit test project to an existing application. This tutorial shows both methods for creating a unit test project. To follow this tutorial, you can use either approach.


2 Answers

Yep, figured it out.

// Arrange.
// .. whatever ..

// Act.
var viewResult = controller.Create(new Post()) as ViewResult;

// Assert.
Assert.IsNotNull(viewResult);
Assert.IsNotNull(viewResult.ViewData.ModelState["subject"]);
Assert.IsNotNull(viewResult.ViewData.ModelState["subject"].Errors);
Assert.IsTrue(viewResult.ViewData.ModelState["subject"].Errors.Count == 1);
like image 142
Pure.Krome Avatar answered Oct 23 '22 11:10

Pure.Krome


You can (also) test the Controller directly (without testing the View) as follows:

// Arrange.
// .. 

// Act.
controller.Create(new Post());  // missing UserName will invalidate Model with "Please specify your name" message

// Assert
Assert.IsTrue(! controller.ModelState.IsValid);
Assert.IsTrue(  controller.ModelState["UserName"].Errors.Any( modelError => modelError.ErrorMessage == "Please specify your name"));
like image 22
Jonathan Avatar answered Oct 23 '22 11:10

Jonathan