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?
NUnit supports out of the box asynchronous methods by wrapping properly executing them in an asynchronous context and unwrapping eventual exception raised by the code itself or by failed assertions. To make sure the runner properly waits for the completion of the asynchronous tests, these cannot be async void methods.
SetUpAttribute (NUnit 2.0 / 2.5)This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called. It is also used inside a SetUpFixture, where it provides the same functionality at the level of a namespace or assembly.
The SetUp attribute is inherited from any base class. Therefore, if a base class has defined a SetUp method, that method will be called before each test method in the derived class.
MsTest is a native unit testing library that comes with Visual Studio from Microsoft. NUnit is an extra Nuget package that needs to be installed on top and interact with the APIs of Visual Studio. Nunit likely doesn't have direct integration into the native APIs like MsTest does.
In NUnit3
[OneTimeSetUp]
public async Task OneTimeSetup()
{
// fixture one time setup code, can use await here
}
[SetUp]
public async Task Setup()
{
// per test setup, can use await here
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With