简体   繁体   中英

How would I reference a viewModel in a unit test?

I have the following action:

public ViewResult Index()
{
    var model = new MyIndexViewModel { TotalTips = (decimal)7.51 };
    return View(model);
}

I would like to write a unit test that verifies that model.TotalTips is 7.51.

I am trying something like this:

[TestMethod]
public void Test()
{
    // Arrange
    var controller = new MyController(_mockRepository.Object);
    MyIndexViewModel test = new MyIndexViewModel{TotalTips = (decimal)7.51};

    // Action
    ViewResult result = controller.Index();

    // Assert
    Assert.AreEqual(result.ViewData.Model.TotalTips, test.TotalTips); // Problem line
}

But I cannot resolve TotalTips on result.ViewData.Model.TotalTips .

I know this is wrong, but cannot figure out how to properly resolve the model I am posting to the Index view.

According to the documentation ViewDataDictionary.Model is typed as object, so you'll have to cast it to your view model type:

var viewModel = (MyIndexViewModel)result.ViewData.Model;
Assert.AreEqual(viewModel.TotalTips, test.TotalTips);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM