Yip*_*Yay 18 .net c# generics moq
假设我有一些通用方法的接口,没有参数:
public interface Interface {
void Method<T>();
}
Run Code Online (Sandbox Code Playgroud)
现在我希望实现这个类的模拟(我正在使用Moq
),我希望模拟这个方法的一些具体类型 - 让我说我在嘲笑Method<String>()
调用.
mock = new Mock<Interface>();
mock.Setup(x => x.Method ????).Returns(String("abc"));
Run Code Online (Sandbox Code Playgroud)
的想法????
应该是明确的-这lambda表达式应该处理的情况时,T
在Method<T>
实际上是一个String
.
有什么方法可以达到想要的行为吗?
Dar*_*rov 20
只是:
mock.Setup(x => x.Method<string>()).Returns("abc");
Run Code Online (Sandbox Code Playgroud)
还要确保您的方法实际返回一些内容,因为当前返回类型定义为void
:
public interface Interface
{
string Method<T>();
}
class Program
{
static void Main()
{
var mock = new Mock<Interface>();
mock.Setup(x => x.Method<string>()).Returns("abc");
Console.WriteLine(mock.Object.Method<string>()); // prints abc
Console.WriteLine(mock.Object.Method<int>()); // prints nothing
}
}
Run Code Online (Sandbox Code Playgroud)
我自己没有使用过Moq,但我希望:
mock.Setup(x => x.Method<string>());
Run Code Online (Sandbox Code Playgroud)
(请注意,您的示例方法具有void返回类型,因此它不应返回任何内容......
归档时间: |
|
查看次数: |
11843 次 |
最近记录: |