【问题标题】:Mocking Generic Method with NSubstitute使用 NSubstitute 模拟泛型方法
【发布时间】:2013-07-27 21:10:17
【问题描述】:

我有一个包含许多通用方法的接口。这些方法根据传入的数据类型执行操作。如何使用 NSubstitute 模拟它?目前,我不得不求助于使用具体类而不是模拟,因为我无法处理将调用该方法的所有可能类型。

public interface IInstanceSource
{
    bool CanCreate<T>();
    T Create<T>();
    void Register<T>(Func<T> creator);
}

    public static IInstanceSource GetInstanceSource()
    {
        var _data = new Dictionary<Type, Func<object>>();
        var a = Substitute.For<IInstanceSource>();
        //code below fails since T is not defined. How do I make the code below accept any type?
        a.WhenForAnyArgs(x=>x.Register(Arg.Any<Func<T>>)).Do(x=> { /* todo */});
        a.CanCreate<T>().Returns(x => _data[typeof (T)]);
        return a;
    }

谢谢。

【问题讨论】:

    标签: c# .net nsubstitute ncrunch


    【解决方案1】:

    NSubstitute 不支持自动设置泛型方法的多个实例。

    我们通常在测试中看到IInstanceSource 的方式是为测试中的特定代码位配置它,因此T 将是已知的。如果单个夹具需要为几个不同的Ts 工作,我们可以通过使用像ConfigureInstanceSource&lt;T&gt;() 这样的辅助方法来简化配置,该方法将为特定的T 执行配置步骤。

    在您的情况下,尽管您似乎希望为所有 IInstanceSource 的假实例设置一个固定的行为,但在这种情况下,我相信您通过手动编写自己的测试替身来解决这个问题是正确的。

    【讨论】:

    • 谢谢。我必须编写一个实现IInstanceSource 的类。它工作得很好。我虽然可能默认支持它,但我没有看到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    相关资源
    最近更新 更多