我有一个抽象类这样的:单元测试类继承抽象类
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;
}
- 因为派生类是取代T
与string
,我认为通过调用基地,就像我在我原来的消息中显示的,我打电话的构造函数,需要Value
,但我打电话给那个采取Format
...
- 要解决这个问题,在我的StringField
I类替换为基础构造函数的调用看起来像这样:
public StringField(int length, string value)
: base(length, value: value)
{ }
类型冲突的intresting情况下,同时使用泛型:)
你的代码工作对我很好,你看生成日志,也许你的DLL被其它进程 –
我更新了我的答案,因为我发现一个问题,解决了这个问题。谢谢你的时间。 –