I’m new to Moq, and having what seems to be a silly problem.
If I perform the setup based on a loop it iwll not match, but if I do the “identicatal” setup by hand I do get a match.
I am using Moq 4.0.10827, from NuGet
My interface being mocked is simple:
public interface IMyInterface
{
string GetValue(string input);
}
The test-entire program is below.
The expected output is identical for both methods, but “Foo” is not printed for Version2()
Code:
class Program
{
static void Main(string[] args)
{
Version1();
Console.WriteLine("---------");
Version2();
Console.WriteLine("---------");
Console.ReadKey();
}
private static void Version1()
{
var mock = new Mock<IMyInterface>();
mock.Setup(x => x.GetValue(It.Is<string>(s => s == "Foo"))).Returns("Foo");
mock.Setup(x => x.GetValue(It.Is<string>(s => s == "Bar"))).Returns("Bar");
IMyInterface obj = mock.Object;
Console.WriteLine(obj.GetValue("Foo"));
Console.WriteLine(obj.GetValue("Bar"));
}
private static void Version2()
{
var mock = new Mock<IMyInterface>();
string[] keys = new string[] { "Foo", "Bar" };
foreach (string key in keys)
{
mock.Setup(x => x.GetValue(It.Is<string>(s => s == key))).Returns(key);
}
IMyInterface obj = mock.Object;
Console.WriteLine(obj.GetValue("Foo")); // Does not match anything
Console.WriteLine(obj.GetValue("Bar"));
}
}
I take it I am missing something.. but what ?
Program output:
Foo
Bar
---------
Bar
---------
Edit: Output from program
Here’s a more generic way, this setup alone will let you return what you get from the parameter.
By using
It.Is<string>(s => s == "Bar")you are probably overwriting first predicate. Try to change the order or string and check it behaves that way.If you want to check values seperetely, you can do something like this
In a loop: