【问题标题】:What calls Dispose() method in c# MSTest unit test?什么在 c# MSTest 单元测试中调用 Dispose() 方法?
【发布时间】:2019-01-14 13:28:42
【问题描述】:

我目前正在审查一个使用 MSTest 并实现 IDisposable 的测试类。测试本身正在测试一个自定义客户端,并且有一个

的实例

RichardSzalay.MockHttp 的 MockHttpMessageHandler

它实现了 IDisposable 接口。

以下代码已添加到类的底部,并在每次测试后被调用。我正在寻找确认什么调用了测试类中声明的 Dispose 方法

public void Dispose()
{
    _mockHttpHandler.Dispose();
}

【问题讨论】:

  • 我强烈怀疑这将取决于您使用的测试框架。请将该信息添加到问题中。另外,您是否尝试过调试并在Dispose 调用上放置一个断点,然后查看堆栈跟踪?
  • 更新了问题,将 MSTest 作为测试框架。调用堆栈仅显示当前断点位置,即测试类中的 Dispose 方法。

标签: c# unit-testing asp.net-core mockhttpmessagehandler


【解决方案1】:

MSTest 使用 as 运算符执行类型转换检查,然后在这种情况下调用 Dispose 方法:

 private void RunTestCleanupMethod(object classInstance, TestResult result)
{
  MethodInfo methodInfo = this.Parent.TestCleanupMethod;
  try
  {
    try
    {
      if (methodInfo != null)
        methodInfo.InvokeAsSynchronousTask(classInstance, (object[]) null);
      Queue<MethodInfo> methodInfoQueue = new Queue<MethodInfo>((IEnumerable<MethodInfo>) this.Parent.BaseTestCleanupMethodsQueue);
      while (methodInfoQueue.Count > 0)
      {
        methodInfo = methodInfoQueue.Dequeue();
        if (methodInfo != null)
          methodInfo.InvokeAsSynchronousTask(classInstance, (object[]) null);
      }
    }
    finally
    {
      (classInstance as IDisposable)?.Dispose();
    }
  }

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多