I've got a strange behavior when using Match.Create
with Moq.
The following code snippet doesn't pass, when I extract Match.Create
as a variable:
var mock = new Mock<IA>();
mock.Object.Method ("muh");
mock.Verify (m => m.Method (Match.Create<string> (s => s.Length == 3)));
public interface IA
{
void Method (string arg);
}
What is the reason?
Thanks both of you. But I found another good solution for this. As in the quick start described, you can also use a method. First I thought it would make no difference, whether I use a variable or method. But obviously Moq is clever enough. So the expression and predicate stuff can be converted into:
public string StringThreeCharsLong ()
{
return Match.Create<string> (s => s.Length == 3);
}
I think this is great, because it reduces the noise in unit tests.
MyMock.Verify (m => m.Method (StringThreeCharsLong());
You're extracting too much. Predicate is enough:
var mock = new Mock<IA>();
Predicate<string> isThreeCharsLong = s => s.Length == 3;
mock.Object.Method("muh");
mock.Verify(m => m.Method(Match.Create<string>(isThreeCharsLong)));
Alternatively, for the same effect but slightly shorter syntax you can use It.Is
matcher with expression parameter:
var mock = new Mock<IA>();
Expression<Func<string, bool>> isThreeCharsLong = s => s.Length == 3;
mock.Object.Method("muh");
mock.Verify(m => m.Method(It.Is<string>(isThreeCharsLong)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With