gpt4 book ai didi

c# - 模拟通用方法

转载 作者:IT王子 更新时间:2023-10-29 04:48:58 24 4
gpt4 key购买 nike

假设我有一些带有泛型方法且没有参数的接口(interface):

public interface Interface {
void Method<T>();
}

现在我希望为这个类实现模拟(我正在使用 Moq )并且我希望为一些具体类型模拟这个方法 - 假设我正在模拟 Method<String>()电话。

mock = new Mock<Interface>();
mock.Setup(x => x.Method ????).Returns(String("abc"));

????的想法应该清楚 - 这个 lambda 表达式应该处理 T 的情况在Method<T>实际上是一个 String .

有什么方法可以实现我想要的行为吗?

最佳答案

简单地:

mock.Setup(x => x.Method<string>()).Returns("abc");

还要确保您的方法实际返回一些东西,因为当前返回类型定义为 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
}
}

关于c# - 模拟通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4408443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com