簡體   English   中英

單元測試類繼承抽象類

[英]Unit testing classes inheriting 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 <>的類

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)
{ }

使用泛型時類型沖突的一個有趣案例:)

我復制粘貼的代碼,對我來說測試將按預期執行:代碼將引發新的NotImplementedException()並且測試通過。

也許您正在執行一些舊的dll:s? 還是“引發新的NotImplementedException()”之前的某些代碼導致了問題? 您可以發布這些代碼行嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM