【问题标题】:Fake generic method with FakeItEasy without specifying type使用 FakeItEasy 伪造泛型方法而不指定类型
【发布时间】:2014-05-16 22:41:55
【问题描述】:

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

例如,假设我们有这个美妙的 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);
    }
}

谢谢!

【问题讨论】:

    标签: c# generics fakeiteasy


    【解决方案1】:

    我不知道有任何方法可以直接执行此操作。我不认为 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);
        }
    }
    

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

    【讨论】:

    • +1 这是一个很好的方法,但我也不相信需要以这种方式设置假货。单元测试通常应该关闭泛型上的类型参数
    • 非常好!我没有具体的例子来展示......更多是为了好奇是否可以(轻松地)完成这样的事情。也许可以使用反射来限制伪设置中的泛型类型?
    • @AdamRalph 是的,但不一定必须以静态方式执行此操作。例如,我正在使用 SpecFlow,我有类似When &lt;type&gt; with Id &lt;id&gt; is retrieved from repository 的步骤。有了上面我就不用为每个.准备一步绑定方法了
    • 我只是用它来让我的所有验证辅助方法在单元测试中默认通过。 A.CallTo(validationService).WithReturnType&lt;bool&gt;().Returns(true); 如果需要,我稍后可以用特定行为覆盖一种方法。
    • 如果您使用的是 C#6,那么您可以通过使用“nameof”来简化重构:A.CallTo(fakeBar).Where(call =&gt; call.Method.Name == nameof(fakeBar.Foo)).WithReturnType&lt;int&gt;().Returns(expected);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多