mercredi 25 mars 2015

How to unit test MVC Controller Action that calls a service associated with the Controller

Ok, i tried. but i can't wrap my head around this.


I have a Controller



public sealed class CourseController : ExtController
{
[HttpPost, PersistState, InRole("")] //TODO [SECURITY] [FIX] UPDATE SECURITY ROLES ]

public ActionResult Create(string[] flags, string name, string code, string description)
{
try
{
var Course = Svc.ProcessOperation("CreateCourse", new
{

Flags = flags.Merge(",")
});



Svc.ProcessOperation("CreateCourseTranslation", new
{
CourseId = Course.EntityID,
LanguageId = JAs.Int32(Svc.Localization.Language.EntityID),
Name = name,
Description = description,
Code = code

});
TempData.PersistStatus("Success");

return View();
}
catch (Exception ex)
{
ModelState.AddModelError("API", ex);
TempData.PersistStatus("Failed");
}
return RedirectToAction("Create");
}
}


Svc is a public property of type Service inside the ExtController abstract class which in turn extends the Controller Class



/// <summary>
/// Represents the exteded controller.
/// </summary>
public abstract class ExtController : Controller
{
#region Properties

/// <summary>
/// Gets the service associated with the controller.
/// </summary>
public Service Svc
{
get
{
return HttpContext.Svc();
}
}

#endregion
}


and here is the Unit Test Code using NUnit



[Test]
public void Create_HttpPost_Action_Returns_Create_View()
{
// Arrange
var customersController = new CourseController();

// Act
var result = customersController.Create(new[] { "None" }, "courseName", "Code", "description") as ViewResult;

// Assert
Assert.IsNotNull(result, "Should have returned a ViewResult");
result.AssertViewRendered().ForView("Create");

}


The Problem is when the Create method is called it needs to use Svc to process the operation, so i guess i have to Mock that! but i can't figure out how.


should i mock the controller! but i can't because its a sealed class! or the ExtController! I am lost and need guidance.


[FWIW] This project is based on Xenta MVC Framework (Open Source) which has this Architecture Overview Xenta Architecture Overview


Aucun commentaire:

Enregistrer un commentaire