Rok*_* Ge 11 c# generics fakeiteasy
我想知道是否有人可以为所有可能的类型(或指定的子类型)伪造泛型方法调用?
例如,假设我们有这个美妙的IBar界面.
public interface IBar
{
int Foo<T>();
}
Run Code Online (Sandbox Code Playgroud)
我可以伪造一个依赖于这个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);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Bla*_*rad 18
我不知道有任何办法直接这样做.我不认为DynamicProxy(FakeItEasy使用)支持开放泛型类型.但是,如果您有兴趣,可以采取一种解决方法.
有一种方法可以指定对假冒的任何方法或属性的调用.查看此通过测试中的Where和WithReturnType位:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
尽管如此,我仍然很好奇这个用途.你有一个实际使用伪造接口作为依赖的示例测试吗?