6
votes

I have a fairly standard set of unit tests.

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public async Task MyClass_DoesStuff()
    {
        //...
        await foo;
    }
}

This was all working fine, but then I needed to downgrade to .NET 4.0. I made the necessary package installations and got everything building. However, now my unit tests no-longer work. Instead, I get these errors:

UTA007: Method MyClass_DoesStuff defined in class MyTestClass does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, return-type as void and should not take any parameter. Example: public void Test.Class1.Test(). Additionally, return-type must be Task if you are running async unit tests. Example: public async Task Test.Class1.Test2()

Perhaps the test runner does not recognize System.Threading.Tasks.Task for .NET 4.0? I installed Microsoft Async, Microsoft BCL Build Components, and Microsoft BCL Portability Pack from NuGet.

Is there a way for me to get asynchronous unit testing working for .NET 4.0?

Edit:

The "duplicate" this was flagged as (TestMethod: async Task TestSth() does not work with .NET 4.0) was for the test not showing up in test explorer, whereas in my case I got the error as I posted. Not a duplicate.

2

2 Answers

3
votes

async and await were introduced in .NET 4.5, so you won't be able to use that syntax in .NET 4.0. However, as I recall, Tasks were introduced in .NET 4.0, so you could probably accomplish your task using Task directly.

[TestMethod]
public Task MyClass_DoesStuff()
{
    Task<Foo> foo = GetSomethingAsync();
    var result = foo.Result;
}
2
votes

The easiest solution is to make your unit test project target .NET 4.5. That way, MSTest will support asynchronous unit tests natively.