c# - 如何对返回 PartialViewResult 的 MVC 操作进行单元测试?

标签 c# model-view-controller action

我有一个 Action 如下:

public PartialViewResult MyActionIWantToTest(string someParameter) 
{
    // ... A bunch of logic
    return PartialView("ViewName", viewModel);
}

当我检查结果时,它有一些属性,但它们要么为 null,要么为空。 唯一有任何内容的属性是 ViewEngineCollection,它不包含任何特定于我的方法的内容。

有没有人有一些测试 PartialViewResult 的示例代码?

最佳答案

假设您有一个看起来像这样的 Action:

public PartialViewResult MyActionIWantToTest(string someParameter)
{
   var viewModel = new MyPartialViewModel { SomeValue = someParameter };
   return PartialView("MyPartialView", viewModel);
}

注意:MyPartialViewModel 是一个只有一个属性的简单类 - SomeValue

NUnit 示例可能如下所示:

[Test]
public void MyActionIWantToTestReturnsPartialViewResult()
{
    // Arrange
    const string myTestValue = "Some value";
    var ctrl = new StringController();

    // Act
    var result = ctrl.MyActionIWantToTest(myTestValue);

    // Assert
    Assert.AreEqual("MyPartialView", result.ViewName);
    Assert.IsInstanceOf<MyPartialViewModel>(result.ViewData.Model);
    Assert.AreEqual(myTestValue, ((MyPartialViewModel)result.ViewData.Model).SomeValue);
}

关于c# - 如何对返回 PartialViewResult 的 MVC 操作进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4485685/

相关文章:

c# - Windows Phone IValueConverter 问题

javascript - 如何将 int 列表从 Javascript (Ajax) 发送到 C#?

c# - Item PropertyChanged 不适用于 observableCollection。为什么?

iOS View 正在根据屏幕大小调整大小,但首次出现时有延迟

c# - 增加 int 数组的更优雅的方法?

php - Codeigniter 3.0.0 - 找不到错误 404 页面

Java Spring MVC 映射问题

vue.js - vuex 未知局部突变类型 : updateValue, 全局类型 : app/updateValue. 突变不起作用

c# - 如何通过引用传递 System.Action?

java - Struts2属性歧义