嘲讽泛型方法与NSubstitute [英] Mocking Generic Method with NSubstitute

查看:875
本文介绍了嘲讽泛型方法与NSubstitute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些通用的方法的接口。这些方法执行基于传入的数据类型的操作。我怎么嘲笑这与NSubstitute?此刻,我不得不求助于使用一个模拟的具体类,而不是因为我不能处理所有可能的类型,该方法将被调用。

I have an interface with a number of generic methods. These methods perform operations based on the type of data that is passed in. How do I mock this with NSubstitute? At the moment, I had to resort to using a concrete class instead of a mock since I cannot handle all possible types that the method will be called with.

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不支持自动设定一个通用方法了多个实例。

NSubstitute doesn't support setting up multiple instances of a generic method automatically.

我们通常会看到的方式 IInstanceSource 在测试中使用的是其配置为被测code特定位,因此 T 将是已知的。如果一个夹具需要工作了几个不同的 T S,我们可以使配置更简单通过让像 ConfigureInstanceSource℃的helper方法; T&GT;() 这会做的配置步骤特定 T

The way we'd normally see IInstanceSource used in a test is to configure it for a specific bit of code under test, so T would be known. If a single fixture needed to work for a few different Ts, we could make configuration simpler by having a helper method like ConfigureInstanceSource<T>() which would do the configurations steps for a specific T.

在你的情况,虽然它看起来像你想为 IInstanceSource 的都是假的情况,在这种情况下,我相信你的手去正确的方式它一个固定的行为-coding自己的测试双。

In your case though it seems like you want a fixed behaviour for all fake instances of IInstanceSource, in which case I believe you are going the right way about it by hand-coding your own test double.

这篇关于嘲讽泛型方法与NSubstitute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆