简体   繁体   English

在 Moq 中验证时允许 *any* 参数值?

[英]Allow *any* parameter value when verifying in Moq?

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.我正在验证是否使用 Moq 调用了一个方法,但它是一个相当复杂的方法签名,我只关心一个特定参数的值。 I know Moq has It.IsAny<T>() , but even then you still have to specify what type the argument should be.我知道 Moq 有It.IsAny<T>() ,但即使那样你仍然必须指定参数应该是什么类型。 Is there a way to just say "I don't care what was passed as this parameter, in terms of type OR value"?有没有办法说“我不在乎这个参数传递了什么,就类型或值而言”?

There isn't a way to do what you're asking, because the Setup argument is an expression that represents strongly-typed C#.没有办法按照您的要求进行操作,因为Setup参数是一个表示强类型 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.此代码无法编译,因为Any()返回object并且Foo()需要一个int参数。

If we try to change Any() to return dynamic :如果我们尝试将Any()更改为返回dynamic

dynamic Any() {
    throw new NotImplementedException();
}

This produces the following error:这会产生以下错误:

CS1963 An expression tree may not contain a dynamic operation CS1963 表达式树可能不包含动态操作

There's simply no way do make this expression generation work for every possible type without requiring a generic argument.如果不需要泛型参数,根本无法使此表达式生成适用于每种可能的类型。

As @StriplingWarrior mentioned you've got to specify the arguments when using Verify .正如@StriplingWarrior 提到的,您必须在使用时指定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.但是,起订量确实提供了Invocations序列(不确定引入了哪个版本,YMMV),因此基本上可以按照您的要求进行操作。

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. ...以下将断言Sum方法被调用一次 - 没有指定任何参数。

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.每个调用条目都有方法 arguments 等,因此您可以构建复杂的匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM