N-Unit Has.Exactly(n).Items断言抛出错误

时间:2018-04-26 15:41:33

标签: c# unit-testing nunit

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

代码:

        [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个属性。

2 个答案:

答案 0 :(得分:1)

避免对此任务的有用性进行任何评论,断言您的模型只有5个属性,您可以使用类似Assert.That(typeof(model).GetProperties().Length == 5);

的内容

答案 1 :(得分: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