I am using Rx and RxUI in a MVVM project and have a view model that queries its data from a WCF service asynchronously. In the unit tests I create a mock object that returns a Task with the expected value.
Here's a general idea of what my view model looks like
public class ViewModel : ReactiveObject
{
private IContext _context;
public ViewModel(IContext context)
{
_context = context;
Observable.FromAsync(() => _context.WcfServiceCall())
.Subscribe(result => {
Children.AddRange(results.Select(r => new ChildViewModel(r).ToList()));
});
}
public ObservableCollection<ChildViewModel> { get; private set;}
}
My unit test looks like this
[TestFixture]
public class ViewModelTest : AssertionHelper
{
[Test]
public void ShouldSetChildren()
{
var c = new Mock<IContext>();
c.Setup(q => q.WcfServiceCall())
.Returns(Task.Run(() => new []{ 1,2,3,4,5,6 })):
var vm = new ViewModel(c.Object);
var p = vm.Children.First(); // this call sometimes fails
...
}
}
The issue I'm having is that I have over 400 tests that do this sort of thing and they all work most of the time but I randomly get failed tests, one or two at a time, that report the sequence has no values. This is unpredictable and random. I can run the tests again after a failure and all succeed. I have added the TestScheduler as described here but the problems persist.
Is there a better way to test methods that make asynchronous method calls?
Edit from Paul Bett's input: I see FromAsync does not take an IScheduler parameter but I do have SubscribeOn and ObserveOn available.
Alternatively, I could call the WCF async method directly and convert the returned Task to an observable. I'm not sure I understand when it is more appropriate to use Observable.FromAsync versus not using it.