C#NUnit没有异步运行测试

时间:2014-10-23 02:02:59

标签: c# .net nunit .net-4.5

我编写了以下测试,尝试使用.NET 4.5中提供的新的async / await关键字:

    [Test]
    public async void DefaultFilesValid()
    {
        LogTest(log);
        var libraryTasks = new List<Task<string>>();
        foreach (var def in LibrariesModel.LibraryDefinitions)
        {
            IViewModel viewModel = (IViewModel)ReflectionUtility.CreateNew(def.ModelType);
            var libraries = def.LibraryFiles.Where(f => def.IsDefaultFile(f)).ToArray();
            foreach(var library in libraries)
            {
                var libraryTask = LoadEmbeddedLibraryAsync(viewModel, library);
                libraryTasks.Add(libraryTask);
            }
        }

        // Wait for the results
        var libraryErrors = await Task.WhenAll(libraryTasks);
        var errors = libraryErrors.SelectMany(m => m);
        Assert.True(!errors.Any(), String.Join(Environment.NewLine, errors));
    }

    private async Task<string> LoadEmbeddedLibraryAsync(IViewModel viewModel, string library)
    {
        return await Task.Factory.StartNew<string>(() =>
        {
            var libraryDef = viewModel.Library;
            var libraryMessage = String.Format("The default library '{0}' of the type '{1}' ", library, libraryDef.LibraryName);
            try
            {
                // Open the library
                viewModel.Open(library, library: true);

                // Check that the hash is as expected
                var fileHash = libraryDef.GetDefaultFileHash(library);
                var hash = viewModel.Source.GetStatewiseHashCode().ToString();
                if (fileHash != hash)
                    return libraryMessage + String.Format("has been modified, model hash was '{0}' but '{1}' was expected.", hash, fileHash);
            }
            catch (Exception ex)
            {
                return String.Format("failed to open: {0}", ExceptionUtility.JoinExceptionMessages(ex));
            }
            return null;
        });
    }

然而,代码是同步执行的,有人可以解释一下我做错了吗?

谢谢, 亚历克斯。

1 个答案:

答案 0 :(得分:2)

将您的单元测试从async void更改为async Task。 NUnit仅支持v2.6.2以后的async void单元测试,并且仅支持v2.9.6 for v3(v3中的支持已在v2.9.7中删除)。 async void测试要求NUnit提供一个特殊的上下文,它会改变await(可能还有StartNew的行为,虽然我还没有测试过。)

作为旁注:

  • 使用Task.Run代替Task.Factory.StartNew。我有一篇描述why
  • 的博客文章
  • 使用Task.Run 调用方法,而不是实现(假)异步方法。我有另一篇博客文章描述why