返回传递给模拟方法的值

Returning the value that was passed into a mocked method

我在接口上有一个方法:

Someclass DoSomething(Someclass whatever);

我无法执行 .Returns(x => x) 因为错误:

cannot convert lambda expression to type Someclass because it is not a delegate type.

有什么想法吗?

看看这些方法重载:

Returns(TResult value)
Returns<T>(Func<T, TResult> valueFunction)

C# 编译器应该选择第二个重载,这对您来说似乎很明显。但实际上 C# 编译器无法从您传递的参数 x => x 中推断出泛型参数 T 的类型。这就是编译器选择非通用版本的方法并尝试将 lambda 转换为 SomeClass 的原因。

要解决此问题,您应该帮助编译器推断泛型参数的类型 T。您可以通过显式指定委托参数的类型来实现:

.Returns((SomeClass x) => x);

或者您可以手动指定 T 的类型

.Returns<SomeClass>(x => x)

您可以像

一样创建someclass和return的实例
someclass cl = new someclass
{
//property initialization
};

mockinstance.Setup(s => s.DoSomething(cl)).Returns(cl);