c# - 如何在单元测试中检查模型属性

标签 c# asp.net-mvc-3 unit-testing razor moq

我有一个 Action 如下:

public ActionResult SaveAndExit()
{
    ViewModel1 viewModel = new ViewModel1();

    return View("Index", viewModel);
}

在单元测试中,我想检查 viewModel 中的 View Reg 是否为空。有什么建议吗

测试:

//act
var result = controller.SaveAndExit(viewModel) as ViewResult;

//assert
//Assert.IsNotNull(!result.Model["Reg"].Equals(null));

最佳答案

我倾向于按如下方式编写断言(在此处使用 Microsoft 测试框架断言 - 您没有指定 nunit):

// Act
ActionResult result = controller.SaveAndExit(viewModel);

// Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
ViewResult viewResult = (ViewResult)result;

Assert.IsInstanceOfType(viewResult.Model, typeof(ViewModel1));
ViewModel1 model = (ViewModel1)viewResult.Model;

Assert.IsNotNull(model.Reg);

关于c# - 如何在单元测试中检查模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191418/

相关文章:

c# - GraphicsPath.AddString() 中具有某些字体和字符的通用 GDI+ 异常

c# - 在 C# 中可靠地重现在 PHP 中实现的遗留密码哈希方法

c# - 如果计算机在保留内存映射文件时挂起,会发生什么情况?

c# - 我们在以下代码中使用 "using statement"的原因是什么?

asp.net-mvc-3 - 如何在 ActionLink 中包含书签/片段?

java - 使用子类测试抽象类中的具体方法

java - 模拟返回列表 future 的外部依赖

c# - 从开源项目学习asp.net mvc 3

c# - 操作无法完成,因为 DbContext 已被释放

typescript - 在 TypeScript 中进行单元测试时, stub 依赖项的正确方法是什么?