mardi 28 juin 2016

returning different values in an NSubstitute mock method with an out parameter

Given a method with which to mock...

public bool TryReceive(out T message, TimeSpan millisecondsToWait)

  • I wish to set different messages on the first two calls, and return true.
  • Subsequent calls return false.

I have tried a few variations, and in either case, the lambda expression is executed once, and never again. NSubstitute seems to be caching the first return value, and using the same value over and over.

I have tried this...

TCR @out;
var mb = container.Resolve<IMessageBuffer<TCR>>();
mb.TryReceive(out @out, Arg.Any<TimeSpan>()).Returns(
            _ => { _[0] = buy; return true; },
            _ => { _[0] = sell; return true; },
            _ => { _[0] = null; return false; });

and I have tried this:

        bool? bs = true;
        TCR @out;
        var mb = container.Resolve<IMessageBuffer<TCR>>();
        mb.TryReceive(out @out, Arg.Any<TimeSpan>()).Returns(
            _ =>
            {
                if (bs == true)
                {
                    _[0] = buy;
                    bs = false;
                    return true;
                }
                if (bs == false)
                {
                    _[0] = sell;
                    bs = null;
                    return true;
                }
                _[0] = null;
                return false;
            });

The only option I can think of is to provide a complete substitute implementation of the buffer for test purposes. My feeling is that given this documentation, it should be possible.

Aucun commentaire:

Enregistrer un commentaire