简体   繁体   English

使用FakeItEasy的假通用方法,无需指定类型

[英]Fake generic method with FakeItEasy without specifying type

I wonder if there is anyway one can fake up a generic method call, for all possible types (or specified sub-types)? 我想知道是否有人可以为所有可能的类型(或指定的子类型)伪造泛型方法调用?

For example, suppose we have this wonderful IBar interface. 例如,假设我们有这个美妙的IBar界面。

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

Can I fake a dependency to this IBar's Foo call, without having to specify T being any specific type? 我可以伪造一个依赖于这个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);
    }
}

Thanks! 谢谢!

I'm not aware of any way to do this directly. 我不知道有任何办法直接这样做。 I don't think DynamicProxy (which FakeItEasy uses) supports open generic types. 我不认为DynamicProxy(FakeItEasy使用)支持开放泛型类型。 However , there's a workaround, if you're interested. 但是 ,如果您有兴趣,可以采取一种解决方法。

There's a way to specify a call to any method or property on a fake . 有一种方法可以指定对假冒的任何方法或属性的调用 Check out the Where and WithReturnType bits in this passing test: 查看此传递测试中的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);
    }
}

Still, though, I'm curious about the use for this. 尽管如此,我仍然很好奇这个用途。 Do you have an example test that actually uses the faked interface as a dependency? 你有一个实际使用伪造接口作为依赖的示例测试吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM