【问题标题】:N-Unit Has.Exactly(n).Items assertion throwing errorN-Unit Has.Exactly(n).Items 断言抛出错误
【发布时间】:2018-10-07 09:28:56
【问题描述】:

为什么下面的断言不起作用?

代码:

        [Test]
        public void CreateNewTemplateTest()
        {
            OnlineSignupModel model = new OnlineSignupModel
            {
                SalesRepId = 68,
                PriceAdvanced = (decimal)22.33,
                PriceComplete = (decimal)44.33,
                PriceMvr = (decimal)6.33,
                SetupFee = (decimal)2.33,
            };

            Assert.That(model, Has.Exactly(5).Items);
        }

错误:

System.ArgumentException : The actual value must be an IEnumerable
Parameter name: actual
   at NUnit.Framework.Constraints.ExactCountConstraint.ApplyTo[TActual](TActual actual)
   at NUnit.Framework.Assert.That[TActual](TActual actual, IResolveConstraint expression, String message, Object[] args)
   at NUnit.Framework.Assert.That[TActual](TActual actual, IResolveConstraint expression)

我试图断言对象中有 5 个属性。

【问题讨论】:

  • OnlineSignupModel 是否派生自 IEnumerable
  • 这可能是XY problem。你到底想做什么?
  • 我试图断言对象中有 5 个属性。
  • 这不是Has.Exactly 的用途。为什么你还要测试是否存在 5 个属性?这是一个类:你要么定义了属性,要么没有。您似乎正在尝试测试属性是否已分配给。这仍然不是 Has.Exactly 的工作。
  • 我理解任务的愚蠢,但它是我的老板分配给我的。

标签: c# unit-testing nunit


【解决方案1】:

您使用错误的约束错误地断言。

有多种方法可以断言模型,但这里有一种。

[Test]
public void CreateNewTemplateTest() {
    //Arrange
    var salesRepId = 68,
    var priceAdvanced = (decimal)22.33,
    var priceComplete = (decimal)44.33,
    var priceMvr = (decimal)6.33,
    var setupFee = (decimal)2.33,

    //Act
    OnlineSignupModel model = new OnlineSignupModel {
        SalesRepId = salesRepId,
        PriceAdvanced = priceAdvanced,
        PriceComplete = priceComplete,
        PriceMvr = priceMvr,
        SetupFee = setupFee,
    };

    //Assert
    Assert.That(
        model.SalesRepId = salesRepId &&
        model.PriceAdvanced == priceAdvanced &&
        model.PriceComplete == priceComplete &&
        model.PriceMvr == priceMvr &&
        model.SetupFee == setupFee, Is.True);
}

考虑查看有关如何使用框架的文档

NUnit Documentation Wiki

【讨论】:

    【解决方案2】:

    避免对此任务的有用性发表任何评论,断言您的模型恰好具有 5 个属性,您可以使用 Assert.That(typeof(model).GetProperties().Length == 5); 之类的东西

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2020-06-13
      • 2019-04-19
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      相关资源
      最近更新 更多