c# - 我应该如何对异常类的序列化进行单元测试?

标签 c# .net unit-testing serialization c#-4.0

像这样对异常类的序列化进行单元测试的最佳方法是什么:

[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 verifierGallio/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/

相关文章:

C# 窗体 : how do you set focus to a DataGridView component on a form?

.net - On On Error Resume Next时出错

.net - HashSet 是 Enumerable.ElementAt<TSource> O(1) 吗?

javascript - 单元测试 angularjs $q.all - promise 永远不会完成

unit-testing - 单元测试 : DRY vs. 可预测性

python - 在 Python 中测试电子邮件实现

c# - 如何监控 Active Directory 用户登录/注销?

c# - 是否可以指定一个范围为 using 指令的程序集?

c# - 如何在一行中合并多个数据表(每个数据表返回一行)

c# - 如何在非托管 C++ dll 中查找调用方程序集名称