【问题标题】:TryUpdateModel fails only in unit tests to update child objectsTryUpdateModel 仅在更新子对象的单元测试中失败
【发布时间】:2012-08-14 06:30:32
【问题描述】:

我能够让以下代码在服务器上运行,但不能在单元测试中运行。在单元测试中,简单属性设置正确,但子对象不正确。我的头撞墙太久了,所以欢迎任何建议。

控制器:

[HttpPost]
public bool Save(int id)
{
        var itemFromRepository = this.itemRepository.FetchById(id);

        if (itemFromRepository != null)
        {
            this.TryUpdateModel(
                itemFromRepository,
                "Item",
                new[] { 
                    "AnIntProperty", 
                    "AStringProperty",
                    "Category.Id"
                });

            if (itemFromRepository.Category!= null)
            {
                itemFromRepository.Category= this.categoryRepository.FetchById(itemFromRepository.Category.Id);
            }

            if (ModelState.IsValid)
            {
                this.itemRepository.Update(itemFromRepository);
                return true;
            }
        }

        return false;
}

单元测试:

    this._controller.ControllerContext = new ControllerContext();
    Item item = this.items.First();
    var updatedCategory = this.categories.Last();
    var updatedStringProperty = "Fake Value";
    var updatedIntProperty = 4;

    var formValues = new FormCollection {
        { "Item.AnIntProperty", updatedStringProperty},
        { "Item.Category.Id", updatedCategory.Id.ToString() },
        { "Item.AStringProperty", updatedIntProperty.ToString() }
    };

    var result = this._controller
        .WithIncomingValues(formValues)
        .Save(item.Id);

通过了:

    Assert.That(
        item.AStringProperty,
        Is.EqualTo(updatedStringProperty));
    Assert.That(
        item.AnIntProperty,
        Is.EqualTo(updatedIntProperty));

这不是:

    Assert.That(
        item.Category,
        Is.Not.Null);
    Assert.That(
        item.Category.Name,
        Is.EqualTo(updatedCategory.Name));

【问题讨论】:

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


    【解决方案1】:

    您是否检查过上一个类别不为空?在下面的代码中,您只更新不为空的值,您可以在两种情况下为类别获取空值。 1. 如果该值当前为 null 并且 2. 可能如果您的 categoryRepository.FetchById 返回一个 null 引用。

    if (itemFromRepository.Category!= null)
    {
         itemFromRepository.Category= this.categoryRepository.FetchById(itemFromRepository.Category.Id);
    }
    

    这两种情况都会导致你的断言失败。

    【讨论】:

      猜你喜欢
      • 2016-07-03
      • 2020-03-09
      • 1970-01-01
      • 2019-09-30
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      相关资源
      最近更新 更多