像这样对异常类的序列化进行单元测试的最佳方法是什么:
[Serializable]
public abstract class TankBaseException : Exception
{
public TankBaseException() : base() { }
public TankBaseException(string message) : base(message) { }
public TankBaseException(string message, Exception innerException) : base(message, innerException) { }
public TankBaseException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.timeStamp = info.GetDateTime(String.Format("{0}.TimeStamp", this.GetType().Name));
this.machineName = info.GetString(String.Format("{0}.MachineName", this.GetType().Name));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
string typeName = this.GetType().Name;
info.AddValue(String.Format("{0}.TimeStamp", typeName), this.timeStamp, this.timeStamp.GetType());
info.AddValue(String.Format("{0}.MachineName", typeName), this.machineName, this.machineName.GetType());
}
public override string Message
{
get
{
return String.Format("{0} (Machine Name: {1}; TimeStamp: {2}",
base.Message, this.MachineName, this.TimeStamp);
}
}
private readonly string machineName = Environment.MachineName;
public string MachineName
{
get { return this.machineName; }
}
private readonly DateTime timeStamp = DateTime.Now;
public DateTime TimeStamp
{
get { return this.timeStamp; }
}
}
这是一个人为的示例,以尽量减少此处的示例代码。它将成为异常类层次结构的一部分。我将在我的单元测试项目中派生它来测试基类层次结构。此外,我将测试任何具有自己附加功能的派生类。
问题是关于以符合 Osherove 的“良好测试支柱”的方式测试类的可序列化方面的最佳方法 - 它们是:
- 值得信赖
- 可维护
- 可读
(或任何其他进行单元测试的指南)。
或者,换句话说,我怎样才能在引入最少数量的混杂变量的同时进行测试?
最佳答案
您可以使用 Exception contract verifier的 Gallio/MbUnit .
契约(Contract)验证器是可配置的内置测试套件,适用于众所周知的代码模式。 MbUnit 特别有一个专门的契约(Contract)验证器,用于测试自定义异常类型,其中还包括序列化测试。
[TestFixture]
public class SampleExceptionTest
{
[VerifyContract]
public readonly IContract ExceptionTests = new ExceptionContract<SampleException>()
{
ImplementsSerialization = true,
};
}
关于c# - 我应该如何对异常类的序列化进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3976999/