Pergunta

I'm struggling to get my head around how to make this test pass:

[Fact]
public void scheduler_test()
{
    var scheduler = new TestScheduler();
    var value1Set = false;
    var value2Set = false;

    Observable.Return(true)
        .Delay(TimeSpan.FromMilliseconds(100), scheduler)
        .Subscribe(_ => value1Set = true);

    Observable.Return(true)
        .Delay(TimeSpan.FromMilliseconds(100), scheduler)
        .Subscribe(async _ =>
        {
            await Task
                .Delay(500)
                .ContinueWith(__ => value2Set = true);
        });

    Assert.False(value1Set);
    Assert.False(value2Set);
    scheduler.AdvanceBy(TimeSpan.FromMilliseconds(500).Ticks);
    Assert.True(value1Set);
    Assert.True(value2Set);
}

It currently fails on the final assertion. I thought that the async subscription would block until the awaited Task has completed, but that appears to not be the case.

Can anyone explain why this isn't working, and how one should go about testing a combined scenario such as this?

Foi útil?

Solução

You can't use the TPL with TestScheduler. Task.Delay will wait 500 real milliseconds, not simulated ones. You need to use an Rx-compatible version of Delay, something like Observable.Timer.

On an unrelated note, don't use async methods in the Subscribe, write something like this instead:

Observable.Return(true)
    .Delay(TimeSpan.FromMilliseconds(100), scheduler)
    .SelectMany(async _ => await Task.Delay(500))
    .Subscribe(
    {
        value2Set = true;
    });
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top