2013-10-22 171 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

我已经解决了这个问题,并更新了我的答案。谢谢你的帮助。 –