MVC 3 - Unit Test Controller Result - unit-testing

I am writing unit tests to test MVC 3 controllers. I want to ensure that that the view that comes back from the controller is the right view. In my unit test I have:
[Test]
public void It_Should_Return_The_Right_Page()
{
FormController fc = this.CreateFormController();
var view = fc.FindX();
Assert.AreEqual("FindX", view.ViewName);
}
In my controller, I have:
public ViewResult FindX()
{
return View();
}
This fails because ViewName is null. If I change the call to say return View("FindX") and explicitly define the view to be returned, it works. However, I would like to avoid this if possible. Is there a generally accepted way to approach this?

It sounds like what you want to convey is: Assert that the default view for this method was returned. One way to convey this is using this line:
var view = fc.FindX();
Assert.IsNull(view.ViewName)
But this doesn't convey your intent very well. One way to convey it more clearly is to create an extension method on ActionResult or ViewResult called AssertIsDefaultView like so:
public static class ActionResultAssertions
{
public static void AssertIsDefaultView(this ActionResult actionResult)
{
var viewResult = actionResult as ViewResult;
Assert.IsNotNull(viewResult);
Assert.IsNull(viewResult.ViewName);
}
}
Then in your test you can say:
var view = fc.FindX();
view.AssertIsDefaultView();
MvcContrib has a set of these assertions (I think the name of the method is AssertViewRendered), but I prefer to just write the extensions myself so I can understand MVC better.

If you don't set a viewname, then isn't ViewName being null the correct and expected outcome, so code your test accordingly.
Assert.IsNull(view.ViewName);

that worked for me
public ViewResult FindX()
{
return View("FindX");
}

Related

Unit test controller using UrlHelper with NSubstitute

I'm using MVC5 and NSubstitute. I'm trying to create unit test to verify the model is being properly created for some controller actions.
The problem I have is that the controller is using a model within which I have something along the lines of:
Url = new UrlHelper(Request.RequestContext).Action("Browse")
Any time I try to test this controller method, I get a null object exception. I have tried a lot of different ways to try and mock the context, but it never seems to quite work. Can anyone help?
I've referred to many SO question including;
ASP.NET MVC: Unit testing controllers that use UrlHelper
Which isn't so helpful to me as I'm using NSubstitute.
I was trying to use a MockHttpContext helper method I had found:
public static T MockHttpContext<T>(this T controller) where T : Controller
{
controller.ControllerContext = new ControllerContext
{
HttpContext = GetHttpContextMock()
};
controller.Url = new UrlHelper(controller.ControllerContext.RequestContext);
return controller;
}
private static HttpContextBase GetHttpContextMock()
{
var routes = new RouteCollection();
var actionExecutingContext = Substitute.For<ActionExecutingContext>();
var httpContextBase = Substitute.For<HttpContextBase>();
var httpServerUtilityBase = Substitute.For<HttpServerUtilityBase>();
var httpResponseBase = Substitute.For<HttpResponseBase>();
var httpRequestBase = Substitute.For<HttpRequestBase>();
var httpSessionStateBase = Substitute.For<HttpSessionStateBase>();
actionExecutingContext.HttpContext.Returns(httpContextBase);
httpContextBase.Request.ApplicationPath.Returns("");
httpContextBase.Response.ApplyAppPathModifier(Arg.Any<string>())
.Returns(ctx => ctx.Arg<string>());
httpContextBase.Request.Returns(httpRequestBase);
httpContextBase.Response.Returns(httpResponseBase);
httpContextBase.Server.Returns(httpServerUtilityBase);
httpContextBase.Session.Returns(httpSessionStateBase);
httpRequestBase.Cookies.Returns(new HttpCookieCollection());
return httpContextBase;
}
I was trying to do the same thing. This worked for me:
controller.Url = Substitute.For<UrlHelper>();
controller.Url.Action(Arg.Any<string>(), Arg.Any<string>()).Returns("something");
Then when I call my controller action, it does not crash when dereferencing the UrlHelper. Of course you have to mock up (NSubstitute) the controller properly. I hope this works. I can post more code for mocking the controller if you need.

Unit testing HttpStatusCode in MVC4 'System.NullReferenceException'

I am trying to unit test HttpStatusCodes in MVC4 but I keep getting a 'System.NullReferenceException' when the controller tries to set the status code on Response, which makes sense as the action is getting called directly. I cant for the life of me work out how to do it without it becoming an integration test. Somebody must have done this, any ideas? See my existing code below.
Controller
public ActionResult Index()
{
Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
Response.Headers.Add("Retry-After", "120");
return View();
}
Test
[Test]
public void IndexActionShouldReturn503StatusCode()
{
//Given
var controller = new HomeController();
//When
var result = controller.Index() as HttpStatusCodeResult;
//Then
result.StatusCode.Should().Be((int)HttpStatusCode.ServiceUnavailable);
}
Note
The requirement is for a friendly 'site down' page so I need to return both a view and the status code.
You're returning a ViewResult, then trying to cast it as a HttpStatusCodeResult in your unit test. Try returning a HttpStatusCodeResult instead of a view.
public ActionResult Index()
{
Response.Headers.Add("Retry-After", "120");
return new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable);
}

Calling an action of another controller - Design consideration for File Uploader - MVC 4

I have a situation where I'm debating how to architect my controllers.
Consider the following controller:
public class FileSharingController : Controller
{
private readonly ICommandBus commandBus;
public FileSharingController(ICommandBus commandBus)
{
this.commandBus = commandBus;
}
[HttpPost]
public ActionResult PrepareMetadata(int blocksCount, string fileName, long fileSize)
{
...
}
[HttpPost]
public ActionResult ClearFileMetadata(string fileName){
...
}
[HttpPost] [ValidateInput(false)] //$.ajax({ data: html5FormDataFileChunk , processData: false ... })
public ActionResult UploadBlock(string fileName, int blockId){
var fileUploadCommand = (FileUploadCommand)ExtractFromSessionData(fileName);
var result = commandBus.Submit(fileUploadCommand);
...
}
public ActionResult CommitFileUploads(string[] filesToCommit){
var commitFileUploadCommand = (CommitFileUploadCommand)ExtractFromSessionData(fileName);
var result = commandBus.Submit(commitFileUploadCommand );
...
}
In this controller, I use the command pattern and pass a model to my commandBus which interfaces with my domain. The first three [HttpPost] methods on the controller are for handling jQuery ajax calls from a responsive file uploading UI.
Consider the situation where a user fills out a form (an interview) and uploads some files along with it. Although the user can upload the files before submitting the form, I don't want the uploaded files to be committed until AFTER they submit the form and it passes validation. That is why the last method on the controller is not an http endpoint. As such I have the following controller:
public class InterviewController : Controller
{
[HttpGet]
public ActionResult UserInterview()
{
InterviewViewModel viewModel = new InterviewViewModel ();
return PartialView(viewModel);
}
[HttpPost] [AllowAnonymous]
public ActionResult UserInterview(InterviewViewModel viewModel)
{
if(ModelState.IsValid)
{
var fileSharingController = new FileSharingController();
fileSharingController.CommitFileUploads(viewModel.Files);
}
return PartialView(viewModel);
}
}
The problem is I'm using IoC to inject a commandBus into the FileSharingController so I cannot just instantiate it with default constructor as I am doing.
My options to consider:
Create a custom controller factory to allow instantiating my controller anywhere in the code.
Turn my FileSharingController in a WebAPI controller and treat as a service
Which is the better design path for this situation? If the latter case, how can I keep the CommitFileUploads() method private? I don't want it to be exposed as an endpoint that can be triggered without first validating the rest of the form.
You can instantiate your controller like this:
ICommandBus commandBus = DependencyResolver.Current.GetService<ICommandBus>();
var fileShareController = new FileSharingController(commandBus);
Generic GetService() method is extension method, so make sure that you have "using System.Web.Mvc;" line in the cs file.
But then, it's better to have helper class that is responsible for keeping/storing already uploaded files, and call it from both controllers, instead instantiating controllers manually.
For example:
public class FileUploadManager
{
public FileUploadManager(ICommandBus commandBus, HttpSessionStateBase sessionState)
{
//....
}
}
and then you call it:
ICommandBus commandBus = DependencyResolver.Current.GetService<ICommandBus>();
var fileShareController = new FileUploadManager(commandBus, this.HttpContext.Session);
Or, if you don't want to use DependencyResolver, you pass ICommandBus to both controller's constructors, and use that reference to instantiate helper class.
simply just create the object of another conroller and use all its public methods.

Is there a way to unit test ASP.NET MVC ViewBag properties set in the view?

Say I have a view with the following code at the top of the page:
#{
ViewBag.Title = "About Us";
Layout = "~/Views/Shared/_Layout.cshtml";
}
And I have a controller method:
public ActionResult About()
{
return View();
}
How can I test that the ViewBag was set properly?
I have tried the following code.
[TestCase]
public void About()
{
var controller = new AboutController();
var ar = controller.About() as ViewResult;
Assert.AreEqual("About Us", ar.ViewBag.Title);
}
But I get the following result when I run the test:
Tests.Controllers.AboutControllerTests.About():
Expected: "About Us"
But was: null
Since both the ViewData and ViewBag use the same storage pattern, you should be able to use ViewData[yourKey] in your tests.
So your test will look like this:
[TestCase]
public void About()
{
var controller = new AboutController();
var ar = controller.About() as ViewResult;
Assert.AreEqual("About Us", ar.ViewData["Title"]);
}
Have you tried
Assert.AreEqual("About Us", controller.ViewBag.Title);
It works for me
The ViewResult returned by a controller has only a reference to the view that should be shown. The view is not even resolved at this time. The code there is never executed by your test.
What you should do is set ViewBag properties in the controller, not the view. Usually, the view will only read such values.
hope it helps
No, you cannot test views like this. The closest you might get is to render the view into a stream writer and then test the generated HTML. It is not something that is commonly done in unit tests. I would recommend you performing web tests in order to verify that the views are correct. You could create web tests with Visual Studio or there's also the free Selenium framework.
For what its worth, I found that the following worked fine:
Assert.AreEqual(_layout, result.ViewBag.Layout);
With result being the ViewResult
[TestMethod]
public async Task GetData() {
CtrlNameController controller = new CtrlNameController();
controller.ViewData["UserId"] = 1;
ViewResult result = await controller.GetData() as ViewResult;
Assert.IsNotNull(result);
}
ViewData["UserId"] is equal to View.UserId

How do I test for TempData being set in MVC 2 where there is a redirect?

When trying to test my MVC 2 controllers, I am having a hard time testing the result of TempData when I'm doing a redirect. It works ok if the result of the controller action is a ViewResult, however, in a redirect, it is RedirectToRouteResult.
So my test is something like this:
var controller = new SubscriptionController(this.dataStorageMock.Object)
{
ControllerContext = MvcMockHelpers.GetControllerContextMock("POST")
};
var actionResult = controller.Create(formCollection);
var redirectResult = (RedirectToRouteResult)actionResult;
// TODO: Need to ensure TempData contains a key "info".
One option is to do the following:
Assert.That(controller.TempData.ContainsKey("info"));
If the result had been a ViewResult it could have been tested like this:
var viewResult = (ViewResult)actionResult;
Assert.That(viewResult.TempData.ContainsKey("info"));
Is there a way to test RedirectToRouteResult the same way as the ViewResult can be tested?
Thanks
Assert.That(controller.TempData.ContainsKey("info")); is exactly what you need.