Rx framework: How to wait for an event to be triggered in silverlight test

Posted by user324255 on Stack Overflow See other posts from Stack Overflow or by user324255
Published on 2010-04-23T14:35:53Z Indexed on 2010/04/23 17:03 UTC
Read the original article Hit count: 360

Hi, I have a ViewModel that starts loading the Model async in the constructor, and triggers an event when the Model is loaded. I got a test working with the silverlight unit test framework, like this :

    bool done = false;

    [TestMethod]
    [Asynchronous]
    public void Test_NoCustomerSelected()
    {
        ProjectListViewModel viewModel = null;
        EnqueueCallback(() => viewModel = new ProjectListViewModel());
        EnqueueCallback(() => viewModel.ModelLoaded += new EventHandler<EventArgs>(viewModel_ModelLoaded));

        EnqueueConditional(() => done);
        EnqueueCallback(() => Assert.IsNotNull(viewModel.FilteredProjectList));
        EnqueueCallback(() => Assert.AreEqual(4, viewModel.FilteredProjectList.Count));

        EnqueueTestComplete();
    }

    void viewModel_ModelLoaded(object sender, EventArgs e)
    {
        done = true;
    }

But I'm beginning playing with Rx Framework, and trying to get my test to work, but so far I have no luck. Here's 2 attempts :

    public void Test_NoCustomerSelected2()
    {
        ProjectListViewModel viewModel = null;
        viewModel = new ProjectListViewModel(eventAggregatorMock.Object, moduleManagerMock.Object);

        IObservable<IEvent<EventArgs>> eventAsObservable = Observable.FromEvent<EventArgs>(
            ev => viewModel.ModelLoaded += ev,
            ev => viewModel.ModelLoaded -= ev);

        eventAsObservable.Subscribe(args => viewModel_ModelLoaded(args.Sender, args.EventArgs));
        eventAsObservable.First();

        Assert.IsNotNull(viewModel.Model);
        Assert.AreEqual(4, viewModel.Model.Count);
    }

    [TestMethod]
    public void Test_NoCustomerSelected3()
    {
        ProjectListViewModel viewModel = null;

        var o = Observable.Start(() => viewModel = new ProjectListViewModel(eventAggregatorMock.Object, moduleManagerMock.Object));

        IObservable<IEvent<EventArgs>> eventAsObservable = Observable.FromEvent<EventArgs>(
            ev => viewModel.ModelLoaded += ev,
            ev => viewModel.ModelLoaded -= ev);

        o.TakeUntil(eventAsObservable)
              .First();

        Assert.IsNotNull(viewModel.Model);
        Assert.AreEqual(4, viewModel.Model.Count);
    }

The first test goes in waiting forever, the second doesn't work because the viewModel is null when it does the FromEvent.

Anyone has a clue on how to do this properly?

© Stack Overflow or respective owner

Related posts about system.reactive

Related posts about reactive-framework