【发布时间】:2023-03-13 12:05:02
【问题描述】:
像这样对异常类的序列化进行单元测试的最佳方法是什么:
[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 的“良好测试的支柱”的方式测试类的可序列化方面的最佳方式——它们是:
- 值得信赖
- 可维护
- 可读
(或任何其他进行单元测试的指南)。
或者,换句话说,如何在引入最少数量的混杂变量的同时进行测试?
【问题讨论】:
-
您是否使用自定义序列化程序?如果没有,那么您要测试标准一吗?什么原因,你不信任 MS?
-
我想确保在 GetObjectData 中序列化的内容在序列化 .ctor 中正确反序列化。我确实写了“...一个异常类 like this”(而不是“...this class”),但即使在这个例子中,也有可能包含拼写错误的魔术字符串,应该对其进行测试, 国际海事组织。
标签: c# .net unit-testing serialization c#-4.0