【问题标题】:how to throw and handle custom exception from unit test如何从单元测试中抛出和处理自定义异常
【发布时间】:2022-11-04 16:05:56
【问题描述】:

我有自定义异常-->

    public CustomException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {  }

我正在为它写一个单元测试——>

    [TestMethod]
    [ExpectedException(typeof(CustomException))]
    public void TestCustomException()
    {
        throw new CustomException(info:SerializationInfo, context:StreamingContext);
    }

错误显示为 SerializationInfo 和 StreamingContext 是类型并且对于给定的上下文无效。

您能否让我知道从单元测试中抛出自定义异常的正确方法是什么?

【问题讨论】:

  • 不遵循您的语法。 info:SerializationInfocontext:StreamingContext 应该代表什么?他们来自哪里?
  • 我想抛出自定义异常,但不确定什么应该是正确的语法,我只是想尝试提及我在 CustomException(SerializationInfo info, StreamingContext context) 中使用的内容
  • 创建一个新的SerializationInfo 和一个新的StreamingContext 并将它们用作参数
  • 虽然不确定你实际实现了什么,但它当然会抛出它。也许您想测试异常中的数据?
  • 这是为了满足该自定义异常方法的代码覆盖率

标签: c# unit-testing exception


【解决方案1】:

这是运行单元测试的内容:

[TestMethod]
[ExpectedException(typeof(CustomException))]
public void TestCustomException()
{
        SerializationInfo info = new SerializationInfo(typeof(CustomException), new FormatterConverter());
        info.AddValue("ClassName", string.Empty);
        info.AddValue("ExceptionMethod", string.Empty);
        info.AddValue("HResult", 1);
        info.AddValue("Source", string.Empty);
        info.AddValue("Message", string.Empty);
        info.AddValue("InnerException", new ArgumentException());
        info.AddValue("HelpURL", string.Empty);
        info.AddValue("StackTraceString", string.Empty);
        info.AddValue("RemoteStackTraceString", string.Empty);
        info.AddValue("RemoteStackIndex", 0);    
        StreamingContext context = new StreamingContext()
        throw new CustomException(info,context);
}

【讨论】:

  • 所以你的问题实际上是“如何实例化 SerializationInfo,以便我可以将其传递给异常的构造函数”,并且您编写了一些似乎可以这样做的代码。此代码满足哪些要求?这是使其编译和运行所需的最低要求吗?这个测试完成了什么?
猜你喜欢
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多