【问题标题】:Unit testing ASP.NET MVC ViewBag properties set in view单元测试视图中设置的 ASP.NET MVC ViewBag 属性
【发布时间】:2020-04-13 11:43:22
【问题描述】:

我有各种需要测试的 ViewBag 设置正确。我从测试一个简单的 ViewBag.Title 开始,然后我将转到其他实际传递动态数据的 ViewBags。

我正在尝试在 Create.cshtml 中测试这个 ViewBag.Title

@{
    ViewBag.Title = "Create";
}

此视图的预订控制器:

    // GET: Booking/Create
    public ActionResult Create()
    {
        return View();
    }

我尝试了以下方法:

    [TestMethod]
    public void BookingTest()
    {
        var controller = new BookingController();
        var ar = controller.Create() as ViewResult;
        Assert.AreEqual("Create", ar.ViewData["Title"]);
    }

也试过了:

    [TestMethod]
    public void BookingTest()
    {
        var controller = new BookingController();
        //var ar = controller.Create() as ViewResult;
        Assert.AreEqual("Create", controller.ViewBag.Title);
    }

两个单元测试都失败并返回以下内容:Message: Assert.AreEqual failed. Expected:<Create>. Actual:<(null)>.

谁能看出我做错了什么?

【问题讨论】:

  • 你不应该习惯依赖 ViewBag。如果可能的话,使用强类型模型会更好。

标签: c# asp.net asp.net-mvc unit-testing


【解决方案1】:

基于

@{
    ViewBag.Title = "Create";
}

您似乎正在实际视图(即 cshtml)文件中设置ViewBag

根据ControllerView 的分离方式,单元测试将无法访问呈现的视图。 ActionResult(在这种情况下为ViewResult)将由框架在运行时执行,以便将必要的数据传递给视图。

要获得预期的行为,您必须从控制器分配 Title

控制器动作:

public ActionResult Create() {
    ViewBag.Title = "Create";
    return View();
}

让您的测试按预期运行。

[TestMethod]
public void BookingTest() {
    //Arrange
    var controller = new BookingController();
    string expected = "Create";

    //Act
    var result = controller.Create() as ViewResult;
    var actual = (string) result.ViewData["Title"];

    //Assert
    Assert.AreEqual(expected, actual);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2014-08-16
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多