1

I have a C# method with an out parameter:

public bool TryGetNext(out Bestellung? bestellung);

When setting up a mock for this method using Moq, how do I:

  1. Correctly handle the out parameter in the Setup?

  2. Make the mock return different values and assign different values to the out parameter on subsequent calls?

0

1 Answer 1

2

Cause i already needed this information twice and hat troubles researching it every time, i post this here.

Lets pretend we have this methode,

public bool TryGetNext(out Bestellung? bestellung);

what makes it special, it does have a Out Parameter usually if you dont care

It.isAny<Bestellung>()

would be right do declare that this setup is acting on any input as long it is of Type Bestellung

In Case of a Out you need to use It.Ref<Bestellung>.IsAny.

How are we get the setup to give us different results every time we call it?

In my case is the Original Methode a DeQueue so i rebuild this.

.Returns((out Bestellung? bestellung) => {}

here we get the variable bestellung we just assign and with the return as usually assign the return value of the method itself.

Queue<Bestellung> bestellungenQueue = new Queue<Bestellung>(
[
  new BestellungBuilder().WithAuftragsNr(123456).Build(),
  new BestellungBuilder().WithAuftragsNr(789456).Build()
]);

Mock<IBestellungRepository> mockRepository = new Mock<IBestellungRepository>();
mockRepository.Setup(m => m.TryGetNext(out It.Ref<Bestellung>.IsAny!))
    .Returns((out Bestellung? bestellung) =>
    {
      if (bestellungenQueue.Count > 0)
      {
        bestellung = bestellungenQueue.Dequeue();
        return bestellung != null; // Return true if not null
      }

      bestellung = null;
      return false; // No more items
    });
Sign up to request clarification or add additional context in comments.

2 Comments

How is this different to stackoverflow.com/questions/1068095/… ?
@mjwills in the part how to get different values on each call, stack overflow encurages questions with self answers and i thought it might help someone or my self if i forget it again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.