简体   繁体   English

是否不支持NUnit异步安装?

[英]NUnit async Setup not supported?

I need to unit test a method which loads with data in async fashion. 我需要对以异步方式加载数据的方法进行单元测试。 I can easily run async tests methods via 我可以轻松地运行异步测试方法

[Test]
public async Task My_test_async() {
 // ... await something
}

But I also want the Setup method to be async. 但我也希望Setup方法是异步的。 Because it prepares some data in mocked Db. 因为它在模拟的Db中准备了一些数据。 This mocked db is of course also async (it has to implement the same interface). 这个模拟的db当然也是异步的(它必须实现相同的接口)。

So my setup method looks like this: 所以我的设置方法如下所示:

[Setup]
public async Task Setup() {
  var db = new InMemoryDbContext();
  // ... add sample data in db context
  // ... then save them
  await db.SaveChangesAsync();
}

But this results in my tests being skipped by NUnit Runner 但这导致我的测试被NUnit Runner跳过 在此输入图像描述

I am using NUnit version 3.0.1, NUnitTestAdapter.WithFramework version 2.0.0 and VisualStudio 2015 with Resharper 9.2 我正在使用NUnit版本3.0.1,NUnitTestAdapter.WithFramework版本2.0.0和VisualStudio 2015与Resharper 9.2

Possible workarounds 可能的解决方法

I can workaround this problem, but neither solution feels nice. 我可以解决这个问题,但两种解决方案都不是很好。

Workaround #1 解决方法#1

Refactor Setup() method to be private, remove the [Setup] attribute from it, and call it in every test method. 重构Setup()方法是私有的,从中删除[Setup]属性,并在每个测试方法中调用它。 That way it can be awaited and tests will execute. 这样就可以等待,测试就会执行。

Workaround #2 解决方法#2

Or I can make the Setup synchronous, and wrap the async code in Task.Run().Result , like this 或者我可以使安装程序同步,并将异步代码包装在Task.Run().Result ,如下所示

var r = Task.Run(() => db.SaveChangesAsync()).Result;

But both workarounds are ugly. 但这两种解决方法都很难看。

Does anyone knows a better solution? 有谁知道更好的解决方案?

In NUnit3 在NUnit3中

[OneTimeSetUp]
public async Task Setup()
{

Work around #2 :D 解决#2:D

[SetUp]
public void Setup()
{
    SetupAsync().Wait();
}

public async Task SetupAsync()
{
    var db = new InMemoryDbContext();
    // ... add sample data in db context
    // ... then save them
    await db.SaveChangesAsync();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM