gpt4 book ai didi

c# - 使用 FakeItEasy 伪造泛型方法而不指定类型

转载 作者:可可西里 更新时间:2023-11-01 08:39:38 25 4
gpt4 key购买 nike

我想知道是否有人可以为所有可能的类型(或指定的子类型)伪造一个通用方法调用?

例如,假设我们有这个美妙的IBar界面。

public interface IBar
{
int Foo<T>();
}

我可以伪造对这个 IBar 的 Foo 调用的依赖,而不必指定 T 是任何特定类型吗?

[TestFixture]
public class BarTests
{
[Test]
public void BarFooDoesStuff()
{
var expected = 9999999;
var fakeBar = A.Fake<IBar>();

A.CallTo(() => fakeBar.Foo<T>()).Returns(expected);

var response = fakeBar.Foo<bool>();

Assert.AreEqual(expected, response);
}
}

谢谢!

最佳答案

我不知道有什么方法可以直接做到这一点。我认为 DynamicProxy(FakeItEasy 使用的)不支持开放的泛型类型。 但是,如果您有兴趣,有一个解决方法。

有一种方法可以specify a call to any method or property on a fake .检查此通过测试中的 WhereWithReturnType 位:

[TestFixture]
public class BarTests
{
[Test]
public void BarFooDoesStuff()
{
var expected = 9999999;
var fakeBar = A.Fake<IBar>();

A.CallTo(fakeBar)
.Where(call => call.Method.Name == "Foo")
.WithReturnType<int>()
.Returns(expected);

var response = fakeBar.Foo<bool>();

Assert.AreEqual(expected, response);
}
}

不过,我还是很好奇它的用途。您是否有实际使用伪造接口(interface)作为依赖项的示例测试?

关于c# - 使用 FakeItEasy 伪造泛型方法而不指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22865825/

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