0

I'm trying to fake a sealed external audio source using FakeItEasy.

I've wrapped the audio source and successfully faked the wrapper, so I know the basics are right. Here's the bit I'm currently stuck on:

The audio source returns isPlaying = true after it's been called with Play(). isPlaying will remain true until the audio clip has finished playing at which point it'll return to false.

I can fake the first part of this with the following code:

A.CallTo(() => fakeAudioSourceWrapper.Play())
    .Invokes(() => fakeAudioSourceWrapper.isPlaying = true)

Which successfully fakes isPlaying being true after the Play function is called. What I'd like to do is then delay a certain time and then make it return false to simulate what happens after the clip has finished playing.

I tried

    A.CallTo(() => fakeAudioSourceWrapper.Play())
        .Invokes(() => fakeAudioSourceWrapper.isPlaying = true)
        .Then
        .Invokes(() => fakeAudioSourceWrapper.isPlaying = false);

with the idea that a call to isPlaying would return true the first time it was called after Play() was called, and return false the second time, but got no joy.

Is there a way to do this?

piersb
  • 609
  • 9
  • 22

1 Answers1

1

Your solution would probably work if Play were called more than once, since you're configuring what Play does (although I think you switched the true and false). I'm guessing from the question that Play is only called once. In that case, you want Play to perform an action that will set up changing behaviour between calls to isPlaying.

Consider the approach in this passing test, where Play causes isPlaying to return true exactly once (the default behaviour for an unconfigured bool-returning Fake's method is to return false):

public interface IAudioSourceWrapper {
    public bool isPlaying {get;set;}
    public void Play();
}

[Fact]
public void PlayThenDoNotPlay()
{
    var fakeAudioSourceWrapper = A.Fake<IAudioSourceWrapper>();
    A.CallTo(() => fakeAudioSourceWrapper.Play())
        .Invokes(() => {
            A.CallTo(() => fakeAudioSourceWrapper.isPlaying).Returns(true).Once();
        });

    fakeAudioSourceWrapper.isPlaying.Should().Be(false);
    fakeAudioSourceWrapper.Play();
    fakeAudioSourceWrapper.isPlaying.Should().Be(true);
    fakeAudioSourceWrapper.isPlaying.Should().Be(false);
}
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111