简体   繁体   English

如何简化 It.IsAny<t> () 用于设置 Mocks 的参数</t>

[英]How to simplify the It.IsAny<T>() parameters for setting up Mocks

In our unit tests we frequently use Mock.Setup .在我们的单元测试中,我们经常使用Mock.Setup This leads to statements such as:这会导致以下陈述:

_mockedModel.Setup(x => x.Method1(It.IsAny<string>(), It.IsAny<object>(),It.IsAny<string>())).Returns(1);
_mockedModel.Setup(x => x.Method2(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<object>())).Returns(1);
_mockedModel.Setup(x => x.Method3(It.IsAny<object>(), It.IsAny<object>(), It.IsAny<string>())).Returns(1);
_mockedModel.Setup(x => x.Method4(It.IsAny<object>(), It.IsAny<object>(), It.IsAny<object>())).Returns(1);

This is quite verbose, and I would like to simplify the It.IsAny<T>() parameters.这很冗长,我想简化It.IsAny<T>()参数。

We have tried doing the following:我们已尝试执行以下操作:

Func<string> s = It.IsAny<string>;
Func<object> o = It.IsAny<object>;
_mockedModel.Setup(x => x.Method1(s(), o(), o())).Returns(1);
_mockedModel.Setup(x => x.Method2(s(), o(), o())).Returns(1);
_mockedModel.Setup(x => x.Method3(o(), o(), s())).Returns(1);
_mockedModel.Setup(x => x.Method4(o(), o(), o())).Returns(1);

But, although this does not give any errors, it does not Setup the Mock.但是,虽然这没有给出任何错误,但它并没有设置 Mock。 Eg Methods 1 to 4 return 0 and not 1.例如,方法 1 到 4 返回 0 而不是 1。

But, although this does not give any errors, it does not Setup the Mock.但是,虽然这没有给出任何错误,但它并没有设置 Mock。 Eg Methods 1 to 4 return 0 and not 1.例如,方法 1 到 4 返回 0 而不是 1。

That is because Moq Setup is explicitly looking for It.IsAny<T>() static method call within the expression in order to configure the setup correctly.这是因为 Moq Setup明确地在表达式中查找It.IsAny<T>() static 方法调用,以便正确配置设置。 That is by design.这是设计使然。

By changing to the function in your attempt to simplify the expression, you force the expression to invoke the method call which returns the default of the generic type argument.通过更改为 function 以尝试简化表达式,您可以强制表达式调用返回泛型类型参数的默认值的方法调用。

So your expression effective becomes所以你的表达效果就变成了

_mockedModel.Setup(x => x.Method1(null, null, null)).Returns(1);
//...

@Nkosi's answer helped me think up a solution. @Nkosi 的回答帮助我想出了一个解决方案。 The solution is to place the It.IsAny() calls inside a property (or method):解决方案是将 It.IsAny() 调用放在属性(或方法)中:

private static string Str => It.IsAny<string>();
private static object Obj => It.IsAny<object>();

This allows the code to be written as follows:这允许代码编写如下:

_mockedModel.Setup(x => x.Method1(Str, Obj, Obj)).Returns(1);
_mockedModel.Setup(x => x.Method2(Str, Obj, Obj)).Returns(1);
_mockedModel.Setup(x => x.Method3(Obj, Obj, Str)).Returns(1);
_mockedModel.Setup(x => x.Method4(Obj, Obj, Obj)).Returns(1);

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

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