【问题标题】:How should I unit test the serialization of an Exception class?我应该如何对 Exception 类的序列化进行单元测试?
【发布时间】: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


【解决方案1】:

您可以使用Gallio/MbUnitException contract verifier

合约验证器是可配置的内置测试套件,适用于众所周知的代码模式。 MbUnit 特别有一个专门的合约验证器,用于测试自定义异常类型,其中也包括序列化测试。

[TestFixture]
public class SampleExceptionTest
{
  [VerifyContract]
  public readonly IContract ExceptionTests = new ExceptionContract<SampleException>()
  {
    ImplementsSerialization = true,
  };
}

【讨论】:

    【解决方案2】:

    你不能。这是一个abstract 类。

    您唯一的选择是拥有它的子类并进行单元测试。

    我想知道为什么它是一个抽象类?它没有抽象方法或属性。

    【讨论】:

    • 好的,是的,我要了那个!我会编辑我的帖子。序列化是个问题。
    • 我已经澄清了,现在,我希望。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2020-11-06
    • 2013-07-16
    • 2011-01-01
    相关资源
    最近更新 更多