使用NSubstitute模拟泛型方法

11

我有一个接口,其中包含许多通用方法。这些方法根据传入的数据类型执行操作。如何使用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;
    }
谢谢。
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
10

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

通常,我们在测试中使用的方式是为要测试的特定代码进行配置,因此将被知道。如果单个夹具需要适用于几个不同的,我们可以通过使用像ConfigureInstanceSource<T>()这样的辅助方法来简化配置步骤,该方法将为特定的执行配置步骤。

但在您的情况下,似乎您希望所有IInstanceSource的虚拟实例都具有固定的行为,在这种情况下,我认为您正在正确地手工编写自己的测试替身。


谢谢。我必须编写一个实现“IInstanceSource”接口的类。它正常工作。我之前认为它可能是默认支持的,而我没有看到它。 - ritcoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,