c# - 最小起订量/单元测试无法捕获异常,除非单步执行代码

标签 c# visual-studio unit-testing moq

我有一个单元测试,它期望一个异常作为返回参数。

如果我通过调试器运行代码,并检查它工作的各种元素。 如果我只是运行所有测试,它不会。

问题必须与该方法是异步的事实有关,就好像我删除了它按预期工作的各种异步元素一样。 (我猜是时间问题)

我的单元测试是;

  [TestMethod]
  [ExpectedException(typeof(System.AggregateException))]
  public void Service_GetDoc_ThrowsExceptionIfNull()
  {
        var nullRepository = new Mock<CCLDomainLogic.Repositories.DocRepository>();
        IDD emptyDoc = null;

        nullRepository
          .Setup<Task<CCLDomainLogic.DomainModels.Doc>>
          (x => x.GetDocAsync(It.IsAny<int>()))
          .Returns(() => Task<CCLDomainLogic.DomainModels.Doc>.Factory.StartNew(() => emptyDoc));

        DocService s = new DocService(nullRepository.Object);

        var foo = s.GetDocAsync(1).Result;
    }            

以及代码(简写为)

    public async Task<Doc> GetDocAsync(int id)
    {
        Stopwatch timespan = Stopwatch.StartNew();
        try
        {
            ...                
            {
                var t = await Task.Run(() => _repository.GetDocAsync(id));
                ...
            }
            timespan.Stop();

            if (t == null)
            {
                throw new ArgumentNullException("DocService.GetDocAsync returned Null Document");
            }

        }
        catch (Exception e)
        {
            throw new Exception("Error in DocService.GetDocAsync", e);
        }
    }

那么我该如何修改这个测试以在运行异步时捕获异常。 作为奖励问题,我可以修改我的单元测试以便检查特定异常,而不是聚合异常吗?

最佳答案

您的测试运行在断言已经运行(或未运行)之后执行的异步代码的原因。 使用调试器只会给异步代码更多的工作时间。 为了测试您的代码,您只需将 MTest 的返回类型更改为 Task 并将 await 添加到相关调用中:

[TestMethod]
[ExpectedException(typeof(System.AggregateException))]
public async Task Service_GetDoc_ThrowsExceptionIfNull()
{
    var nullRepository = new Mock<CCLDomainLogic.Repositories.DocRepository>();
    IDD emptyDoc = null;

    nullRepository
        .Setup<Task<CCLDomainLogic.DomainModels.Doc>>(x => x.GetDocAsync(It.IsAny<int>()))
        .Returns(() => Task<CCLDomainLogic.DomainModels.Doc>.Factory.StartNew(() => emptyDoc));

    DocService s = new DocService(nullRepository.Object);

    var foo = await s.GetDocAsync(1).Result;
}  

关于c# - 最小起订量/单元测试无法捕获异常,除非单步执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359423/

相关文章:

c# - asp.net core 2.2 不使用 WebApp Azure 配置中设置的 ConnectionString

c# - 序列不包含任何元素服务器端

asp.net - 在 Visual Studio 中保存一些 javascript 文件后自动运行 gulp 任务

C# 单元测试用例帮助

java - 将 HttpUnit+junit 组织为独立应用程序的最佳设计

c++ - 单元测试调用标准库的 C++ 方法的模式

c# - 帮助找到最深的拼写检查子控件

c# - Unity容器可以动态加载程序集吗?

visual-studio - Visual Studio : Is there a "move class to different namespace" refactoring?

visual-studio - 如何根据打开的解决方案使 Visual Studio 看起来不同?