Reputation: 29993
I'm verifying that a method was called with Moq, but it's quite a complex method signature and I just care about the value of one particular argument. I know Moq has It.IsAny<T>()
, but even then you still have to specify what type the argument should be. Is there a way to just say "I don't care what was passed as this parameter, in terms of type OR value"?
Upvotes: 1
Views: 654
Reputation: 3193
As @StriplingWarrior mentioned you've got to specify the arguments when using Verify
.
However Moq does provide the Invocations
sequence (unsure what version it was introduced, YMMV) so it is possible to basically do what you're asking.
For the following interface:
public interface IFoo
{
public void Sum(int a, int b, out int sum);
}
... the following will assert that the Sum
method was invoked once - without specifying any parameters.
var fooMock = new Mock<IFoo>();
var foo = fooMock.Object;
foo.Sum(1, 2, out var sum);
Assert.That(fooMock.Invocations.Count(x => x.Method.Name.Equals(nameof(IFoo.Sum))), Is.EqualTo(1));
Each invocation entry has the method, arguments etc so you can build complex matches.
Upvotes: 1
Reputation: 156504
There isn't a way to do what you're asking, because the Setup
argument is an expression that represents strongly-typed C#. For example, consider the following approach:
void Main()
{
Setup(() => Foo(Any()));
}
void Setup(Expression<Action> expression)
{
}
void Foo(int i)
{
}
object Any()
{
throw new NotImplementedException();
}
This code doesn't compile, because Any()
returns an object
and Foo()
requires an int
argument.
If we try to change Any()
to return dynamic
:
dynamic Any() {
throw new NotImplementedException();
}
This produces the following error:
CS1963 An expression tree may not contain a dynamic operation
There's simply no way do make this expression generation work for every possible type without requiring a generic argument.
Upvotes: 3