简体   繁体   中英

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

In our unit tests we frequently use 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.

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. Eg Methods 1 to 4 return 0 and not 1.

But, although this does not give any errors, it does not Setup the Mock. Eg Methods 1 to 4 return 0 and not 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. 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.

So your expression effective becomes

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

@Nkosi's answer helped me think up a solution. The solution is to place the It.IsAny() calls inside a property (or method):

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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