【问题标题】:How can I mock a singleton class with NSubstitute?如何使用 NSubstitute 模拟单例类?
【发布时间】:2017-04-20 08:09:14
【问题描述】:

我有一个单例类,像这样:

public class XConnector : IXConnector
        {

            private static readonly Lazy<XConnector> instance = 
                    new Lazy<XConnector>(() => new XConnector());

            public static XConnector Instance => instance.Value;

            private XConnector()
            {
            }

            public async Task<XConnector> GetData(XConnector con)
            {
            }
      }

如何使用 NSubstitute 模拟这个类?

另一方面:我想要这样的东西

var target = Substitute.For<IXConnector>();

这是我调试此代码时的快速观看

欢迎任何帮助。

【问题讨论】:

  • 有什么问题?如果IXConnector 是一个接口(我想),Substitute.For&lt;IXConnector&gt;(); 应该可以完美工作。
  • 您可以使用 Mark Seemann 的 Ambient Context 模式。这将允许您注入一个实例,同时仍然提供单例的意图。
  • CrmConnector如何依赖XConnector
  • 无论如何我认为__target-member 不是你想的那样(但是不确定内部实现)。只需使用您已经拥有的代码var target = Substitute.For&lt;IXConnector&gt;();。这将为您提供接口的代理实例。但是它不知道你的单身人士的任何事情。也许你应该展示你是如何使用模拟的。
  • 这里没有单例,只是一个涉及的接口实例。因此,请展示您使用 target 所做的事情。

标签: c# .net unit-testing mocking nsubstitute


【解决方案1】:

我不记得环境上下文模式的实现,我手头没有书。但是,它看起来像这样:

public class XConnector : IXConnector
{
    private static IXConnector _instance = new XConnector();

    private XConnector()
    {
    }

    public static IXConnector Current
    { 
       get
       {
           return _instance;
       }
       set 
       {
           // Think about thread-safety
           // Check for null?
           _instance = value;
       }
    }

    public async Task<XConnector> GetData(XConnector con)
    {
    }
}

那么你的测试可以这样做:

XConnector.Current = Substitute.For<IXConnector>();

您的功能代码可以做到这一点,使用默认实例或假实例:

XConnector.Current.GetData(...);

【讨论】:

  • 你让我走上了正确的道路。但我不认为我有我的答案。因为实例是只读的
  • 这很重要吗?如果你想用假的替换实例,你将需要一些方法来设置它,当前的设计排除了构造函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多