开发者

Testing a get action with view model

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 t开发者_高级运维est:

[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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜