ASP.NET MVC Unit Testing Controllers - Repositories
Posted
by Brian McCord
on Stack Overflow
See other posts from Stack Overflow
or by Brian McCord
Published on 2010-05-27T14:41:24Z
Indexed on
2010/05/27
14:51 UTC
Read the original article
Hit count: 234
This is more of an opinion seeking question, so there may not be a "right" answer, but I would welcome arguments as to why your answer is the "right" one.
Given an MVC application that is using Entity Framework for the persistence engine, a repository layer, a service layer that basically defers to the repository, and a delete method on a controller that looks like this:
public ActionResult Delete(State model)
{
try
{
if( model == null )
{
return View( model );
}
_stateService.Delete( model );
return RedirectToAction("Index");
}
catch
{
return View( model );
}
}
I am looking for the proper way to Unit Test this. Currently, I have a fake repository that gets used in the service, and my unit test looks like this:
[TestMethod]
public void Delete_Post_Passes_With_State_4()
{
//Arrange
var stateService = GetService();
var stateController = new StateController( stateService );
ViewResult result = stateController.Delete( 4 ) as ViewResult;
var model = (State)result.ViewData.Model;
//Act
RedirectToRouteResult redirectResult = stateController.Delete( model ) as RedirectToRouteResult;
stateController = new StateController( stateService );
var newresult = stateController.Delete( 4 ) as ViewResult;
var newmodel = (State)newresult.ViewData.Model;
//Assert
Assert.AreEqual( redirectResult.RouteValues["action"], "Index" );
Assert.IsNull( newmodel );
}
Is this overkill? Do I need to check to see if the record actually got deleted (as I already have Service and Repository tests that verify this)? Should I even use a fake repository here or would it make more sense just to mock the whole thing?
The examples I'm looking at used this model of doing things, and I just copied it, but I'm really open to doing things in a "best practices" way.
Thanks.
© Stack Overflow or respective owner