On VS 2013, I can't get this async test to fail.
I have xUnit 1.8.0.1539 (installed from nuget), with the xUnit Test Runner VS extension (0.99.5). All current, AFAIK.
I happen to also have Moq, AutoFixture, and FluentAssertions reference in the unit test, but I don't think that matters (but I'm admitting it in case it does).
I have done async unit tests in other areas of my solution, and they work.
I'm missing something with this newly created tests, and I can't tell what I'm missing or doing wrong.
NOTE The SUT code is not meant to be complete. I'm just trying to get the red light first, before I write the code to make the test go green.
Here's the test code:
using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace MobileApp.Proxy.Test { public class WhenRetrievingPriceDataFromClient { [Fact] public async Task GroupReportIsReturnedWithSomeData() { // arrange var sut = new Client(); // act var actual = await sut.GetReportGroupAsync(); // assert // Xunit test Assert.Null(actual); Assert.NotNull(actual); // FluentAssertions actual.Should().BeNull(); actual.Should().NotBeNull(); } } }
And here is the SUT code:
using System; using System.Diagnostics; using System.Net.Http; using System.Threading.Tasks; using MobileApp.Proxy.Properties; namespace MobileApp.Proxy { public class Client { public async Task<ReportGroup> GetReportGroupAsync() { return await Task.FromResult(new ReportGroup()); } } }
Obviously, this test should fail! The Asserts for Null and NotNull can't both succeed, so my conclusion is that the test is exiting before it finishes getting the response from the SUT.
What did I miss?
OR, is there a better way I should have started an async test to make sure it fails before writing the SUT code?
You need xUnit 1.9 for async
unit tests to work correctly.
Async tests are supported in xUnit v1.9 or later. If you're stuck with an earlier version, you'll need to do something like this:
[Fact] public void GroupReportIsReturnedWithSomeData() { GroupReportIsReturnedWithSomeDataAsync().Wait(); } private async Task GroupReportIsReturnedWithSomeDataAsync() { // arrange var sut = new Client(); // act var actual = await sut.GetReportGroupAsync(); // assert // Xunit test Assert.Null(actual); Assert.NotNull(actual); // FluentAssertions actual.Should().BeNull(); actual.Should().NotBeNull(); }
Basically, the test method blocks until the async test method completes, whether it'd due to successful completion or fault (e.g., a failed assertion). In the case of a fault, the exceptions will propagate to the main test thread through Wait()
.
You may want to pass a timeout to Wait()
so your test will fail if it hasn't completed after a certain amount of time. As written, the test could block indefinitely if the async method never completes.
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