【问题标题】:Unit test custom NLog target单元测试自定义 NLog 目标
【发布时间】:2015-01-21 04:50:27
【问题描述】:

我编写了一个 NLog 目标,旨在获取 NLog LogEventInfo 并将其写入 Azure 的 API 服务。我无法为记录器编写单元测试,因为我不知道如何拦截记录到 APIServices.Log.Trace 的消息。

这是目标定义:

namespace Ariel.Mobile.Logging
{
using System.Collections;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Tracing;

using Ariel.Library;

using Microsoft.WindowsAzure.Mobile.Service;

using Ninject;

using NLog;
using NLog.Targets;

/// <summary>
/// Class to be used with NLog to write error and debug data to Azure for storage.
/// </summary>
[Target("Azure")]
public class AzureTarget : Target
{
    #region Fields

    /// <summary>
    /// Defines the mappings between NLog and Azure levels.
    /// </summary>
    private static readonly IDictionary<LogLevel, TraceLevel> LevelMap =
        new Dictionary<LogLevel, TraceLevel>
            {
                { LogLevel.Trace, TraceLevel.Debug }, 
                { LogLevel.Debug, TraceLevel.Debug }, 
                { LogLevel.Info, TraceLevel.Info }, 
                { LogLevel.Warn, TraceLevel.Warn }, 
                { LogLevel.Error, TraceLevel.Error }, 
                { LogLevel.Fatal, TraceLevel.Fatal }
            };

    /// <summary>
    /// Gets or sets the Azure service to which messages will be sent.
    /// </summary>
    private readonly ApiServices services;
    #endregion

    public AzureTarget()
    {
        services = new ApiServices(ServiceConfig.Config);
    }

    #region Methods

    /// <summary>
    /// Method accepting NLog logging events to be transmitted to Azure.
    /// </summary>
    /// <param name="logEvent">The NLog event which needs to be persisted.
    /// </param>
    protected override void Write(LogEventInfo logEvent)
    {
        this.services.Log.Trace(LevelMap[logEvent.Level], logEvent.Message, logEvent.Exception);
    }

    #endregion
}
}

如何在单元测试中截获记录到 APIServices.Log.Trace 的消息?

【问题讨论】:

    标签: c# azure nlog


    【解决方案1】:

    看看Microsoft Fakes

    您将能够使用 Shim 来拦截呼叫。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2015-01-11
      相关资源
      最近更新 更多