Testing a Controller

Taken from stackoverflow – http://stackoverflow.com/questions/18865257/how-to-unit-test-an-action-when-return-type-is-actionresult

I wanted to know how to test that I’m populating the view index correctly, but couldn’t get to the actual model.

I wanted to ensure that I was populating the following class

 public class ViewIndex
  public string Headline { get; set; }
  public string Snippet { get; set; }
  public string VideoContent { get; set; }
  public PressReleaseIndex PressReleaseContent { get; set; }
  public ICollection<Carousel> CarouselContent { get; set; }

Through the unit test – i pumped some test data into the repositories

  var stub = MockRepository.GenerateStub<IArticleDAL>();
   stub.Stub(s => s.GetContent("headling content")).IgnoreArguments().Return(ReturnHeadlineContent);
   stub.Stub(t => t.GetFirstOfType(enumArticleType.PressRelease)).IgnoreArguments().Return(ReturnedPressRelease);
   stub.Stub(r => r.GetAllOfATypeFromATime(enumArticleType.Carousel, DateTime.Now)).IgnoreArguments().Return(localCarousel);

Using the following code I was able to pick out the info

   ActionResult returnResults = new HomeController(stub).Index();
   Assert.IsInstanceOfType(returnResults, typeof(ViewResult));
   ViewResult vResult = returnResults as ViewResult;

   if (vResult != null)
    Assert.IsInstanceOfType(vResult.Model, typeof(ViewIndex));
    ViewIndex model = vResult.Model as ViewIndex;
    if (model != null)
     Assert.IsTrue(model.CarouselContent.Count == 2);
     Assert.IsTrue(model.Headline == "headling content");
     Assert.IsTrue(model.PressReleaseContent.Headline == "Press release headline");


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s