简体   繁体   中英

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. Because it prepares some data in mocked Db. This mocked db is of course also async (it has to implement the same interface).

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 在此输入图像描述

I am using NUnit version 3.0.1, NUnitTestAdapter.WithFramework version 2.0.0 and VisualStudio 2015 with Resharper 9.2

Possible workarounds

I can workaround this problem, but neither solution feels nice.

Workaround #1

Refactor Setup() method to be private, remove the [Setup] attribute from it, and call it in every test method. That way it can be awaited and tests will execute.

Workaround #2

Or I can make the Setup synchronous, and wrap the async code in Task.Run().Result , like this

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

But both workarounds are ugly.

Does anyone knows a better solution?

In NUnit3

[OneTimeSetUp]
public async Task Setup()
{

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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