I'm new to Xamarin and have been using Xamarin studio for about a week, and have been struggling to get the Unit testing to function properly with async calls. I'm hoping I just don't understand how to use it properly and it actually works right with async calls, but I'm starting to wonder. If I have a test method:
[Test] async public void Create () { var charactersObject = new Characters ("unitTestToken"); Characters.Character expected = new Characters.Character (); expected.userId = "123456"; expected.name = "TestUser"; var actual = await charactersObject.Create (expected); Assert.AreEqual (expected.userId, actual.userId, "User Id are not equal"); Assert.AreEqual (expected.name, actual.name, "Name are not equal"); Assert.AreNotEqual (0, actual.id); }
and have the following code:
async public Task Create (Character newCharacter) { byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(newCharacter.toJSON()); string url = BASE_URL + VERSION + "Characters"; var request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url)); request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add ("authorization", authorization_token); request.ContentLength = byteArray.Length; Stream writer = await request.GetRequestStreamAsync (); writer.Write (byteArray, 0, byteArray.Length); await writer.FlushAsync (); writer.Close (); WebResponse ar = await request.GetResponseAsync (); var s = new StreamReader(ar.GetResponseStream ()); string json = await s.ReadToEndAsync (); return new Character (json); }
I can clearly see that the test method completes and reports that it passes before it ever even hits the asserts. In fact if an assertion ends up failing, I see the test method passing in the test runner and I get an exception for the failed assertion. It seems that my Create method is still finishing up but passes control back to the unit test on one of the long running async calls.
I've verified that the code does actually work correctly outside of the unit test runner. I've also tried googling and searching the Xamarin docs, but it seems that most information is about the IOS unit testing framework which is more advanced then the android one.
Thanks for any help anyone has to offer.