繁体   English   中英

使用NSubstitute模拟通用方法

[英]Mocking Generic Method with NSubstitute

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

谢谢。

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

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

在你的情况下,虽然你似乎想要一个针对IInstanceSource所有虚假实例的固定行为,在这种情况下,我相信你通过手动编码你自己的测试双重正确的方式。

暂无
暂无

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

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