Question

I have the following controller action:

public ActionResult Edit(int id)
{
   var news = newsRepository.GetNewsByID(id);

   Mapper.CreateMap<News, NewsEditModel>();
   var newsEditModel =
      (NewsEditModel)Mapper.Map(news, typeof(News), typeof(NewsEditModel));

   return View(newsEditModel);
}

And the corresponding test:

[Test]
public void Edit_should_render_view()
{
   // Arrange
   var id = 1;
   var newsEditModel = new NewsEditModel();

   // Act
   var actual = sut.Edit(id);

   // Assert
   actual
      .AssertViewRendered()
      .WithViewData<NewsEditModel>()
      .ShouldBe(newsEditModel);
}

In the NUnit GUI I get the following error:

MyProject.Web.UnitTests.Controllers.NewsControllerTests.Edit_should_render_view: MvcContrib.TestHelper.AssertionException : was MyProject.Web.Common.ViewData.NewsEditModel but expected MyProject.Web.Common.ViewData.NewsEditModel

I don't know how to write the corresponding unit test. Can someone please help me?

Was it helpful?

Solution

Your test is comparing two different instances of NewsEditModel - one instance that you create in your test code, and the other that is created in the action method.

If you want to examine the model property values as part of your test, you could do this:

var model = actual
  .AssertViewRendered()
  .WithViewData<NewsEditModel>();

// Check that model is not null
Assert.That(model, Is.Not.Null);  

// Check that model ID is same as passed into action method
Assert.That(model.Id, Is.EqualTo(1));
// or alternatively ...
model.Id.ShouldBe(1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top