单元测试和模拟调用另一个服务的传统包装器

时间:2017-05-15 14:24:29

标签: c# unit-testing mocking

我很乐意删除这个问题,如果提供重复的话。在这方面缺乏知识使得寻找解决方案变得更加困难。

我们开始实施单位&整个组织的集成测试;从新项目开始。

我们完全拥有的测试代码看起来很简单,我们可以利用很多资源。

另一方面,测试调用第三方服务的代码要困难一些。我知道模拟是我们应该做的事情,尽管有点难以弄清楚特定代码片段的实际实现。

在这种特殊情况下,我们有一个新的库,它将位于业务层和业务层之间。第三方异常记录器(Sentry) - 因此它是一个传统的包装器。

举个例子,下面的代码是精简的摘录。

接口

public interface IExceptionLogging
{
    void Capture(string endpointKey, string message, params KeyValuePair<string, string>[] tag);
    void Capture(string endpointKey, Exception exception, params KeyValuePair<string, string>[] tag);
}

摘要,有助于强制执行构造函数

public abstract class ExceptionLogging : IExceptionLogging
    {
        internal Dictionary<string, Uri> LoggerEndpoints;

        protected ExceptionLogging(Dictionary<string, Uri> loggerEndpoints)
        {
            LoggerEndpoints = loggerEndpoints;
        }

        public abstract void Capture(string endpointKey, string message, params KeyValuePair<string, string>[] tag);
        public abstract void Capture(string endpointKey, Exception exception, params KeyValuePair<string, string>[] tag);

    }

实施

public class GetSentry : ExceptionLogging
{
    private Dictionary<string, RavenClient> _clients = new Dictionary<string, RavenClient>();

    public GetSentry(Dictionary<string, Uri> loggerEndpoints)
        : base(loggerEndpoints)
    {
        LoggerEndpoints.ToList().ForEach(ep =>
        {
            _clients.Add(ep.Key, new RavenClient(ep.Value.ToString()));
        });
    }

    public override void Capture(string endpointKey, Exception ex, params KeyValuePair<string, string>[] tag)
    {
        RavenClient client = _clients[endpointKey];
        if (client != null)
        {
            SentryEvent se = new SentryEvent(ex);
            tag.ToList().ForEach(t => se.Tags.Add(t));
            client.Capture(se);

        }
    }    

    public override void Capture(string endpointKey, string message, params KeyValuePair<string, string>[] tag)
    {
        RavenClient client = _clients[endpointKey];
        if (client != null)
        {
            SentryEvent se = new SentryEvent(message);
            tag.ToList().ForEach(t => se.Tags.Add(t));
            client.Capture(se);
        }
    }

测试这样的东西的方法是什么?

如上所述,如果有有效的副本,我将很乐意删除此Q.我不确定从哪里开始。

0 个答案:

没有答案
相关问题