如何为属性中的异常创建单元测试

时间:2019-04-17 10:54:31

标签: c# unit-testing attributes

我有属性类:

public class MyAttributeAttribute : Attribute
{
    public MyAttributeAttribute(string proeprty)
    {
        this.TestProperty = proeprty;
    }

    private string property;
    public string TestProperty
    {
        get
        {
            return property;
        }
        set
        {
            if (value.Length > 10)
            {
                throw new InvalidOperationException("Lenght of property is longer then 10");
            }
            else
            {
                property = value;
            }
        }
    }
}

我在许多方法中使用它。如您所见,它引发异常。我正在为此属性创建单元测试,如下所示:

[TestMethod]
public void MyTestMethod()
{
    Exception exception = null;
    try
    {
        MyAttributeAttribute myAttributeAttribute = new MyAttributeAttribute("");
    }
    catch (InvalidOperationException ex)
    {
        exception = ex;
    }

    Assert.IsInstanceOfType(exception, typeof(InvalidOperationException));
}

这是为属性类创建单元测试的好方法吗?还有其他方法可以创建单元测试吗?

0 个答案:

没有答案