A controller in my ASP.NET MVC application pre-populates form data displayed by my view according to a couple of fairly straight forward rules.
It seems like this would be a good thing to cover in my unit testing. But the only way I could see to verify the correct data is placed in the form, would be to extract the logic from the controller in what feels like an unnatural way.
Can someone suggest ways to approach this?
All the examples I've found of unit testing controllers seemed very trivial, such as verifying it returned the expected type of view. I'm not sure I even see the value in that.
You can test by casting the returned object to the appropriate class, instead of using their base class (which is returned by default)
For example, to test the default AccountController you'd so something like this:
var controller = new AccountController();
var result = controller.LogOn() as ViewResult;
var model = result.Model as LogOnModel;
Assert.IsTrue(model.RememberMe); // assuming you "pre-populated" enabled the checkbox
Checking if the returned object is filled with the right data does not seem "unnatural" to me, or did you meant it differently?
I would agree that testing the type of view returned would be somewhat pointless. However, testing that the expected "view" was returned along with its correct data would be a valid test case IMO.
For example here is a singular edit test case for an edit controller. Note, that this example is making use of Moq and Nunit but that aside it's fairly straight forward.
Note, that that ViewResult is cast to the expected view model and the assertions are then made against the expected contact.
Test:
[Test]
public void Edit_Get_Should_Lookup_Contact_From_Repository_And_Return_Edit_View()
{
// arrange
var _repository = new Mock<IContactRepository>();
var expectedContact = new Contact
{
First = "first",
Last = "last",
Email = "mail#test.com"
};
var mockContext = new Mock<ControllerContext>();
_repository.Setup(x => x.GetById(It.IsAny<int>())).Returns(expectedContact);
var controller = new ContactController(_repository.Object)
{
ControllerContext = mockContext.Object
};
// act
var result = controller.Edit(1) as ViewResult;
var resultData = (Contact)result.ViewData.Model;
// assert
Assert.AreEqual("Edit", result.ViewName);
Assert.AreEqual(expectedContact.First, resultData.First);
Assert.AreEqual(expectedContact.Last, resultData.Last);
Assert.AreEqual(expectedContact.Email, resultData.Email);
}
Controller:
[HttpGet]
public ActionResult Edit(int id)
{
var contact = _repository.GetById(id);
return View("Edit", contact);
}
Related
I have the following test method that is being used to test a controller.
[TestMethod()]
public void ResetTest()
{
var target = new Mock<PROJECT.Reset.Controllers.ResetController>();
//var target = new PROJECT.Reset.Controllers.ResetController();
FormCollection form = new FormCollection();
form.Set("username","domain\\username");
form.Set("password","testpass123");
form.Set("confirmpassword","testpass123");
ViewResult expected = new ViewResult();
expected.ViewName = "Reset";
expected.ViewData.Model = rm;
ActionResult action = target.Object.;
action = target.Object.Reset(form);
ViewResult actual = (ViewResult)action;
Assert.AreEqual(expected, actual);
}
If I use the:
var target = new Mock<PROJECT.Reset.Controllers.ResetController>();
Then the action is being evaluated as null. If I change this to the line of code below that which is uncommented then the action is being set. Any ideas what might be causing this behaviour?
Why are you mocking this? It seems that this is your actual SUT (solution under test). So, you should not mock it at all.
Your understanding about Mocking framework is may be incorrect. You should not mock the object which is you are going to test (controller object in your case). You can/do mock only for dependency objects.
Ex : Repository objects and etc.
I'm starting to implement a service layer to my MVC project to thin down some bloated controllers (it also has repository / unitofwork pattern).
My question is if you have a complicated view model for a page with lots of child objects etc, and quite a lot of logic going on behind the scenes (to give you an idea the controller the original developer wrote had almost 4000 lines of code!!) is it OK to have multiple services going off doing their thing? or should I just have one big ReportService which does everything?
My controller is starting to look like this? and if I carry on I could end up having quite a lot of different services being called to build up the view model.
Does this look OK or is it starting to go in the wrong direction?
public ViewResult Index(int? reportId)
{
// get the base report object
var reportService = new ReportService();
var report = reportService.GetByReportId(reportId);
var model = Mapper.Map<Report, ReportViewModel>(report);
// get the current active user
var userService = new UserService();
var user = userService.GetCurrentUser();
model.User = Mapper.Map<User, ReportViewModel.UserViewModel>(user);
// get the first unread message
var messageService = new MessageService();
var message = messageService.GetFirstUnread(user.Id);
model.Message = Mapper.Map<Message, ReportViewModel.MessageViewModel>(message);
// get the category navigation
var categoryService = new CategoryService();
var categoryNavigation = categoryService.GetCategoryNavigation(report.Id);
model.CategoryNavigation = Mapper.Map<IEnumerable<Category>, IEnumerable<ReportViewModel.CategoryNavigationViewModel>>(categoryNavigation);
return View(model);
}
It's fine to have multiple small services in your controller. However, there is one thing that's wrong here:
You services should be available through the entire controller and injected through the constructor to achieve loose-coupling.
So something like this:
private readonly IReportService _reportService;
private readonly IUserService _userService;
public SomeConstructor(IReportService reportService, IUserService userService, etc.)
{
_reportService = reportService;
_userService = userService;
// etc
}
That does look like a good approach, an alternative approach would to be split some of this up by using Child Actions - the best solution will depend upon your specific use case though.
If, for example, the ViewModel property CategoryNavigation was being used by the view to create a sort of navigation 'widget' that might be useful in several different Views, you might be better spliting this off into a ChildAction e.g.
[ChildActionOnly]
public ActionResult CategoryNavigationWidget(int reportId)
{
// get the category navigation
var categoryService = new CategoryService();
var categoryNavigation = categoryService.GetCategoryNavigation(report.Id);
return PartialView(categoryNavigation);
}
Any View could then render that ChildAction by going:
#{ Html.RenderAction("CategoryNavigationWidget", "Report",
new { reportId = Model.ReportId }); }
Whether or not this is a good idea will probably depend upon whether or not the 'widget' is reusable.
I am very new to unit testing even though i have been coding for a very long time. I want to make this a part of my way of development. I run into blocks on how to unit test things like a collection. I generally have my jQuery script calling ASP.Net Server side methods to get data and populate tables and the like. They look like
Get_*Noun*()
which generally returns a JsonResult. Any ideas on what and how to test these using Unit tests using MSTest?
You should be able to test this just like anything else, provided you can extract the values from the JsonResult. Here's a helper that will do that for you:
private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
{
var property =
jsonResult.Data.GetType().GetProperties()
.Where(p => string.Compare(p.Name, propertyName) == 0)
.FirstOrDefault();
if (null == property)
throw new ArgumentException("propertyName not found", "propertyName");
return (T)property.GetValue(jsonResult.Data, null);
}
Then call your controller as usual, and test the result using that helper.
var jsonResult = yourController.YourAction(params);
bool testValue = GetValueFromJsonResult<bool>(jsonResult, "PropertyName");
Assert.IsFalse(testValue);
(I am using NUnit syntax, but MSUnit shouldn't be far off)
You could test your JsonResult like this:
var json = Get_JsonResult()
dynamic data = json.Data;
Assert.AreEqual("value", data.MyValue)
Then in the project that contains the code to be tested, edit AssemblyInfo.cs file to allow the testing assembly access to the anonymous type:
[assembly: InternalsVisibleTo("Tests")]
This is so the dynamic can determine the type of anonymous object being returned from the json.Data value;
This is the best blog I've found on this subject.
My favorite was the 4th approach using dynamics. Note that it requires you to ensure that the internals are visible to your test project using [assembly:InternalsVisibleTo("TestProject")] which I find is a reasonably good idea in general.
[TestMethod]
public void IndexTestWithDynamic()
{
//arrange
HomeController controller = new HomeController();
//act
var result = controller.Index() as JsonResult;
//assert
dynamic data = result.Data;
Assert.AreEqual(3, data.Count);
Assert.IsTrue(data.Success);
Assert.AreEqual("Adam", data.People[0].Name);
}
You could use PrivateObject to do this.
var jsonResult = yourController.YourAction(params);
var success = (bool)(new PrivateObject(jsonResult.Data, "success")).Target;
Assert.IsTrue(success);
var errors = (IEnumerable<string>)(new PrivateObject(jsonResult.Data, "errors")).Target;
Assert.IsTrue(!errors.Any());
It's uses reflection similar to David Ruttka's answer, however it'll save you a few key strokes.
See http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx for more info.
Here's a small extension to easily convert a Json ActionResult into the object it represents.
using System.Web.Mvc;
public static class WebExtensions
{
public static T ToJson<T>(this ActionResult actionResult)
{
var jsonResult = (JsonResult)actionResult;
return (T)jsonResult.Data;
}
}
With this, your 'act' in the test becomes smaller:
var myModel = myController.Action().ToJson<MyViewModel>();
My suggestion would be to create a model for the data returned and then cast the result into that model. That way you can verify:
the structure is correct
the data within the model is correct
// Assert
var result = action
.AssertResultIs<JsonResult>();
var model = (UIDSearchResults)result.Data;
Assert.IsTrue(model.IsValid);
Assert.AreEqual("ABC", model.UIDType);
Assert.IsNull(model.CodeID);
Assert.AreEqual(4, model.PossibleCodes.Count());
I'm having difficulty testing controllers. Original my controller for testing looked something like this:
SomethingController CreateSomethingController()
{
var somethingData = FakeSomethingData.CreateFakeData();
var fakeRepository = FakeRepository.Create();
var controller = new SomethingController(fakeRepository);
return controller;
}
This works fine for the majority of testing until I got the Request.IsAjaxRequest() part of code. So then I had to mock up the HttpContext and HttpRequestBase. So my code then changed to look like:
public class FakeHttpContext : HttpContextBase
{
bool _isAjaxRequest;
public FakeHttpContext( bool isAjaxRequest = false )
{
_isAjaxRequest = isAjaxRequest;
}
public override HttpRequestBase Request
{
get
{
string ajaxRequestHeader = "";
if ( _isAjaxRequest )
ajaxRequestHeader = "XMLHttpRequest";
var request = new Mock<HttpRequestBase>();
request.SetupGet( x => x.Headers ).Returns( new WebHeaderCollection
{
{"X-Requested-With", ajaxRequestHeader}
} );
request.SetupGet( x => x["X-Requested-With"] ).Returns( ajaxRequestHeader );
return request.Object;
}
}
private IPrincipal _user;
public override IPrincipal User
{
get
{
if ( _user == null )
{
_user = new FakePrincipal();
}
return _user;
}
set
{
_user = value;
}
}
}
SomethingController CreateSomethingController()
{
var somethingData = FakeSomethingData.CreateFakeData();
var fakeRepository = FakeRepository.Create();
var controller = new SomethingController(fakeRepository);
ControllerContext controllerContext = new ControllerContext( new FakeHttpContext( isAjaxRequest ), new RouteData(), controller );
controller.ControllerContext = controllerContext;
return controller;
}
Now its got to that stage in my controller where I call Url.Route and Url is null. So it looks like I need to start mocking up routes for my controller.
I seem to be spending more time googling on how to fake/mock objects and then debugging to make sure my fakes are correct than actual writing the test code. Is there an easier way in to test a controller? I've looked at the TestControllerBuilder from MvcContrib which helps with some of the issues but doesn't seem to do everything. Is there anything else available that will do the job and will let me concentrate on writing the tests rather than writing mocks?
Thanks
You can use some of the libraries that give you out of the box some of these objects. For example RhinoMock, NMock ... etc. I personally use Moq - it's good enough and free. What i like most in Moq is the linq expressions.
Most mocking engine will do all this for you. I use RhinoMocks but there are a lot more available. Also Moles is very new and interesting mocking engine (this generally comes with Pex which is yet more ammo in your unit testing arsenal)
MvcContrib + RhinoMocks. Check out the TestControllerBuilder in the MvcContrib.TestHelper library. Here's the official write-up: http://mvccontrib.codeplex.com/wikipage?title=TestHelper#Examples.
Here's an example of mocking a controller out for testing a UrlHelper: ASP.NET MVC: Mock controller.Url.Action
Here's a short explanation of how to use the TestControllerBuilder: http://codebetter.com/blogs/kyle.baley/archive/2008/03/19/testcontrollerbuilder-in-mvccontrib.aspx
Instead of mocking stuff, you can pass IAjaxRequest to constructor. Or make it base constructor class property (and use property injection). Or you can make your constructor implement IAjaxRequest and then apply global action filter on base constructor class that will setup IAjaxRequest.
This will help to abstract many things, including HttpContext stuff. Just don't abstract IHttpContext, abstract IUserContext, ISessionStorage, IAuthentication, IRequestDetails...
Another way is to use model binder directly on methods where you need specific information. See this post for example. You can make binder that will give you IsAjaxRequest, then you just make action to accept this parameter. Works very well because information is provided exactly to the method that needs it, not to the whole controller.
I am trying to test the User.IsInRole("Administrator") in my application, and actually trying to assign the User Role to ("Administrator") so that my test will pass. I am using Scott Hanselman's MvcMockHelpers to do this, and at the moment I have the following test.
[Test]
public void Create_CanInsertNewArticleView_IsNotNull()
{
// Arrange
var controller = new ArticleController();
MockRepository mockRepo = new MockRepository();
var fakeContext = MvcMockHelpers.FakeHttpContext(mockRepo, "~/Article/Create");
fakeContext.User.IsInRole("Administrator");
// Act
Article fakeArticle = FakeObjects.ReturnFakeArticle();
var result = controller.Create(fakeArticle) as ViewResult;
// Assert
Assert.IsNotNull(result);
}
However the actual controller's User is null at the moment.
Can anyone help me out and tell me what the correct test should be, to User.IsInRole("Administrator")
Thanks for your help and time
Johann
See this related answer for details.
Here's the code snippet from the other answer converted to Rhino Mocks:
var user = new GenericPrincipal(new GenericIdentity(string.Empty), null);
var httpCtx = MockRepository.GenerateStub<HttpContextBase>();
httpCtx.User = user;
var controllerCtx = new ControllerContext();
controllerCtx.HttpContext = httpCtx;
sut.ControllerContext = controllerCtx;
You'll have to mock an IPrincipal for your user object, set it up so that .IsInRole("Administrator") returns true, and then set your fakeContext up to return that IPrincipal for the.User property. It would be something like this:
EDIT: It turns out the OP is using Rhino Mocks, and the code I provided was for Moq. Here's an attempt att writing Rhino code, although I have never actually used Rhino myself. The original Moq code can be found below.
In Rhino Mocks, you'll want to add another helper method, or change the current one, so you have the following:
public static HttpContextBase FakeHttpContext(this MockRepository mocks, string url, IPrincipal user)
{
// Do the same setup as Scott does...
// ...and add this:
SetupResult.For(context.User).Return(user);
mocks.Replay(context);
return context,
}
Then you declare and set up your IPrincipal mock object like this before the call to FakeHttpContext, and send the mock object in as the third parameter.
In Moq:
fakeContext = MvcMockHelpers.FakeHttpContext("~/Article/Create");
fakeUser = new Mock<IPrincipal>();
fakeUser.Expect(usr => usr.IsInRole(It.IsAny<String>())).Returns(true);
fakeContext.Expect(context => context.User).Returns(fakeUser.Object);
(Disclaimer: It was a while since I wrote a unit test, and this code has not been tested even for compilation errors. Hence, there might be some wrinkles that need to be ironed out before you can use this code, but you get the general idea...)