0

使用 c#、nunit、selenium 进行自动化。我想为我的测试用例使用属性 [Test, Pairwise] 来验证可以使用任何有效值发布对象。我有包含所有有效值的字典,但是 [Values()] - 需要 const 作为参数,而 ReadOnlyCollection(正如这里建议的那样)不适用于它。 我遇到错误:属性 agument 必须是属性参数类型的常量表达式、typeof 表达式或数组表达式。

class ObjectBaseCalls : ApiTestBase
{
    static ReadOnlyCollection<string> AllTypes = new ReadOnlyCollection<string>(new List<string>() { "Value1", "Value 2" });

    [Test, Pairwise]
    public void ObjectCanBePostedAndGeted([Values(AllTypes)] string type)
    {
        //My test
    }
}
4

2 回答 2

0

这里有两个不同的问题。

错误“属性参数必须是属性参数类型的常量表达式、类型表达式或数组表达式”来自编译器。它描述了 .NET 中任何属性构造函数的限制,而不仅仅是 NUnit 的。如果要在构造函数本身中传递参数,则必须使用常量值。

但是,您似乎不想在构造函数中传递参数。相反,您希望引用单独声明的列表。NUnit 有一组属性可以做到这一点。您应该使用其中之一,例如,ValueSourceAttribute...

public class ObjectBaseCalls : ApiTestBase
{
    static ReadOnlyCollection<string> AllTypes = new ReadOnlyCollection<string>(new List<string>() { "Value1", "Value 2" });

    [Test]
    public void ObjectCanBePostedAndGeted([ValueSource(nameof(AllTypes))] string type)
    {
        //My test
    }
}

或者,由于该方法只有一个参数,因此您可以使用TestCaseSourceAttribute...

public class ObjectBaseCalls : ApiTestBase
{
    static ReadOnlyCollection<string> AllTypes = new ReadOnlyCollection<string>(new List<string>() { "Value1", "Value 2" });

    [TestCaseSource(nameof(AllTypes))]
    public void ObjectCanBePostedAndGeted(string type)
    {
        //My test
    }
}

这些中的任何一个都应该起作用。你在这里使用哪一个是风格偏好的问题。

第二个问题是您使用PairWiseAttribute. Values当您有一个使用or指定的多个参数的测试并且您希望 NUnit 以各种方式组合它们时使用它(与其他几个“组合属性”一起使用ValueSource。在使用单个参数的情况下,它什么都不做。这就是我删除的原因它来自我上面的例子。

如果您实际上打算编写一个包含多个参数的测试并让 NUnit 决定如何组合它们,我认为您需要问一个不同的问题来解释您要完成的工作。

于 2020-02-24T17:22:50.150 回答
0

我找到了解决方案,它对我有用。我为每个对象参数创建了带有参数名称的枚举和带有参数名称和参数值的字典,并将枚举用于我的对象构造函数 PairWiseAttribute。

public class MyElement : BaseElement
{  
    public enum Types { Type1, Type2, Type3, Type4}
    public Dictionary<Types, string> AllTypes = new Dictionary<Types, string>()
    {
        { Types.Type1, "Value 1" },
        { Types.Type2, "Value 2" },
        { Types.Type3, "Value 3" },
        { Types.Type4, "Value 4" },
    };
    public enum Category { Category1, Category2, Category3, Category4}
    public Dictionary<Category, string> Categories = new Dictionary<Category, string>()
    {
        { Category.Category1, "Value 1" },
        { Category.Category2, "Value 2" },
        { Category.Category3, "Value 3" },
        { Category.Category4, "Value 4" },
    };
    public MyElement(Types type, Category category)
    {
        type = AllTypes[type];
        category = Categories[category];
    }
}
public class Test
{
    [Test, Pairwise]
    public void ValidBaseCheckElementCalls
    (
        [Values(Types.Type1, Types.Type2, Types.Type3, Types.Type4)] Types objType,
        [Values(Category.Category1, Category.Category2, Category.Category3, Category.Category4)] Category objCategory,
    )

    {
        MyElement element = new MyElement(objType, objCategory);
    }

}
于 2020-02-25T09:25:11.270 回答