2013-10-22 177 views
0

我有一個抽象類這樣的:單元測試類繼承抽象類

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... 
} 

然後,我有一個繼承字段類<>

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; 
} 

- 因爲派生類是取代Tstring,我認爲通過調用基地,就像我在我原來的消息中顯示的,我打電話的構造函數,需要Value,但我打電話給那個採取Format ...
- 要解決這個問題,在我的StringField I類替換爲基礎構造函數的調用看起來像這樣:

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

類型衝突的intresting情況下,同時使用泛型:)

+0

你的代碼工作對我很好,你看生成日誌,也許你的DLL被其它進程 –

+0

我更新了我的答案,因爲我發現一個問題,解決了這個問題。謝謝你的時間。 –

回答

1

我複製粘貼的你代碼,對我來說測試按預期執行:代碼拋出一個新的NotImplementedException()並且測試通過。

也許你正在執行一些舊的DLL:■?或者,「拋出新的NotImplementedException()」之前的一些代碼導致了問題?你可以發佈這些代碼行嗎?

+0

我張貼在我原來的職位唯一的例外是二傳手的第一道防線。所以我想它一定是老dll的,奇怪的是我清理和重建,仍然得到這個... –

+0

我已經解決了這個問題,並更新了我的答案。謝謝你的幫助。 –