我刚刚完成了我的第一节单元测试课程,但是我对自己的逻辑被复制和粘贴感到沮丧。经过一些搜索,我发现[TestCaseSource]或[TestCase]是我可能需要的,但是当我使用[TestCaseSource]时,我得到以下消息
结果消息:在sourceName上指定的TestCaseSourceAttribute必须引用静态字段、属性或方法。
或者是[TestCase]
属性参数必须是属性参数类型的常量表达式、类型表达式或数组创建表达式。
下面是我使用[TestCaseSource]的代码(我已经删除了testCaseInput中的其他项目,以使它更容易阅读)
private SomeFormValidator SomeFormValidator;
private static MyClass _myClass { get; set; }
private readonly object[] testCaseInput =
{
new object[] { typeof(MyClass), "MyClass is required", _myClass },
};
[SetUp]
public void Setup()
{
SomeFormValidator = new SomeFormValidator ();
_myClass = new MyClass();
}
[Test, TestCaseSource("testCaseInput")]
public void Should_have_error_message_when_property_is_null(string message, object property)
{
var result = SomeFormValidator.ShouldHaveValidationErrorFor(x=> x.MyClass , property);
result.WithErrorMessage(message);
}下面是我使用[TestCase]的代码(为了便于阅读,我删除了其他项目)
private SomeFormValidator SomeFormValidator;
const MyClass _myClass = new MyClass();
[SetUp]
public void Setup()
{
SomeFormValidator = new SomeFormValidator();
}
[Test]
[TestCase("MyClassis required", _myClass )]
public void Should_have_error_message_when_property_is_null(string message, object property)
{
var result = SomeFormValidator.ShouldHaveValidationErrorFor(aup => aup.MyClass, property);
result.WithErrorMessage(message);
}发布于 2017-02-10 00:41:59
对于TestCaseSource属性,应该使用static成员:
private static readonly object[] testCaseInput = ...属性是元数据,在编译时应该知道。您正在尝试将MyClass实例传递给属性。但是类实例只能在运行时创建。实际上,您只可以将常量(例如字符串、布尔值或数字)、typeof表达式(即可以传递typeof(MyClass))或数组创建表达式(例如new [] { 1, 2, 3 })传递给atrributes。
在这种情况下,可以将错误消息和属性名称传递给测试方法:
[TestCase("MyClass is required", "MyClass")]
public void BlahBlah(string message, string propertyName)https://stackoverflow.com/questions/42149432
复制相似问题