单元测试类继承抽象类

时间:2013-10-22 10:17:59

标签: c# unit-testing inheritance abstract-class

我有一个这样的抽象类:

public abstract class Field<T>
{
    private int _length;
    public int Length
    {
        get
        {
            return _length;
        }
        protected set
        {
            if (value <= 0)
            {
                throw new ArgumentOutOfRangeException("The length must be greater than 0");
            }
            else
            {
                _length = value;
            }
        }
    }

    private T _value;
    public T Value 
    {
        get
        {
            if (_value == null) throw new ArgumentException("Field does not have any value set");
            return _value;
        }
        set
        {
            //here obviously I have some code to check the value and assign it to _value
            //I removed it though to show what the problem is

            throw new NotImplementedException();
        }
    }

    public Field(int length, T value)
    {
        Length = length;
        Value = value;
    }

    public Field(int length)
    {
        Length = length;
    }

    //some abstract methods irrelevant to the question...
}

然后我有一个继承Field&lt;&gt;

的类
public class StringField : Field<string>
{
    public StringField(int length, string value)
        : base(length, value)
    { }

    public StringField(int length)
        : base(length)
    { }

    //implementation of some abstract methods irrelevant to the question...
}

当我运行这样的测试时,它很好并且传递(构造函数抛出一个正确的异常):

[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Constructor_LengthOnly_LengthZero_ShouldThrowArgumentOutOfRangeException()
{
    int length = 0;
    StringField sf = new StringField(length);

    //should throw exception
}

但是当我运行这个测试时,构造函数不会抛出,即使它应该抛出NotImplementedException:

[TestMethod]
[ExpectedException(typeof(NotImplementedException))]
public void Constructor_LengthAndValue_ValidLength_TextTooLong_ShouldThrowNotImplementedException()
{
    int length = 2;
    string value = "test";

    StringField sf = new StringField(length, value);

    //should throw exception
}

我做错了吗?我不认为我错过了什么,是吗?谢谢。

- 编辑 -

原来一切都还好,这里发生了什么:
- 在Field我有另一个属性和构造函数,如下:

enprivate string _format;
public string Format 
{ 
    get 
    { 
        return _format; 
    }
    protected set
    {
        _format = value;
     }
}

public Field(int length, string format)
{
    Length = length;
    Format = format;
}

- 由于派生类正在用T替换string,我认为通过调用我在原始消息中显示的基类,我调用的构造函数为Value,但我打电话给那个Format ...的人 - 解决这个问题,在我的StringField类中,我替换了对基础构造函数的调用,如下所示:

public StringField(int length, string value)
    : base(length, value: value)
{ }

使用泛型时类型冲突的有趣情况:)

1 个答案:

答案 0 :(得分:1)

我复制粘贴你的代码,对我来说测试按预期执行:代码抛出一个新的NotImplementedException()并且测试是通过的。

也许你正在执行一些旧的dll:s?或者“抛出新的NotImplementedException()”之前的一些代码导致问题?你可以发布这些代码行吗?