Click here to Skip to main content
15,944,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there, gurus.

I'm sure a lot of you were thinking 'Thank goodness THAT guy disappeared', but I'm here to disappoint you.

My question this time about using Moq with C# to create a mock that will return each letter of a supplied string each time it is called. A simplified example of what I want is:
var sourceText = "abcdefg";
var myMock = new Mock<IThingy>():
myMock.Setup((mm) => mm.NextChar()).Returns(() => { =some code= });

var result = myMock.NextChar(); // should return "a";
result = myMock.NextChar(); // should return "b";

I know I could do this with Sequence(), but that involves hardcoding the return values, which I don't want to do.

What I have tried:

I tried using yield return, but yield is not valid in an anonymous method.
I tried setting up a method that uses yield return, and that would be called by =some code=, but that method would need to return an IEnumerable<string> which means =some code= returns a collection, not a single consecutive character each time.
Updated 11-Aug-20 1:28am

1 solution

var sourceText = "abcdefg";
var index = 0;
var myMock = new Mock<IThingy>();
myMock.Setup(m => m.NextChar()).Returns(() => sourceText[index++]);

var result = myMock.Object.NextChar(); // returns "a";
result = myMock.Object.NextChar(); // returns "b";
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900