首页 > 解决方案 > 什么在 c# MSTest 单元测试中调用 Dispose() 方法?

问题描述

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

RichardSzalay.MockHttp 的 MockHttpMessageHandler

它实现了 IDisposable 接口。

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

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

标签: c#unit-testingasp.net-coremockhttpmessagehandler

解决方案


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();
    }
  }

推荐阅读