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.
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 );
});
}
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