Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit Async Testing in Xamarin Not Working

I'm new to the C# world, trying to give Xamarin an evaluation. I've been making a small web api library, and it has been going smoothly so far, but now that I'm trying to test networking components, I'm having some trouble.

OS:           OS X 10.9.1
Xamarin:      4.2.2 (build 2)
Library:      PCL targeting 4.0 (Profile158)
Nunit target: Mono / .NET 4.5

The class / method:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;

namespace LibTest
{
    public class AsyncTest
    {
        public async Task<string> DoTest()
        {
            return await new HttpClient().GetStringAsync( "http://www.reddit.com/.json?limit=1" );
        }
    }
}

The NUnit test class / case:

using System;
using NUnit.Framework;
using LibTest;

namespace LibTestTests
{
    [TestFixture]
    public class LibTestTest
    {
        [Test]
        public async void TempTest()
        {
            string data = await new AsyncTest().DoTest();

            Assert.IsNotNull( data );
            Assert.IsNull( data );
        }
    }
}

All of my other tests seem to be working (parsing, etc), but this one just goes right by, acting as if it passed, but I don't see how it could have, with the contradictory assertions.

Is this not supported currently, or am I incorrect in my implementation?

If I make it synchronous with ContinueWith() / Wait(), it works as expected, but obviously I don't want to have duplicate implementations in my library, just to pass the tests.

like image 812
Josh Avatar asked Nov 30 '22 19:11

Josh


1 Answers

NUnit does support async Task unit tests; unfortunately, Xamarin is using an older version of NUnit that does not. However, I do not recommend synchronously blocking on the task directly because that will complicate your error path testing (exceptions are wrapped in an AggregateException).

I have an AsyncContext type in my AsyncEx library that can be used as such:

[Test]
public void TempTest()
{
    AsyncContext.Run(async () =>
    {
        string data = await new AsyncTest().DoTest();

        Assert.IsNotNull( data );
        Assert.IsNull( data );
    });
}
like image 119
Stephen Cleary Avatar answered Dec 04 '22 20:12

Stephen Cleary