gpt4 book ai didi

c# - C# 中使用 ILogger 进行单元测试静态方法 ILoggerFactory 为 Null

转载 作者:行者123 更新时间:2023-12-02 02:41:16 27 4
gpt4 key购买 nike

大家

我正在尝试对我的代码进行单元测试,但是我无法让 ILoggerFactory 工作

这是我的单元测试代码(可能不正确):

using NUnit.Framework;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Moq;
using System;
using MyProgramVIP.Bots.Presenter;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Utils;

namespace MyProgramVIPTest
{
public class TestsExample
{
[SetUp]
public void Setup() {

}

[Test]
public void TestExample1()
{
//Mocks
var mockLogger = new Mock<ILogger<TicketPresenter>>();
mockLogger.Setup(
m => m.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.IsAny<object>(),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()));

var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(() => mockLogger.Object);

//Construción del modelo necesario para la prueba
ConversationData conversationData = new ConversationData();
conversationData.ticket = new Ticket();
conversationData.response = new Response();

//Invocación del método a probar
TicketPresenter.getPutTicketMessage(conversationData);

//Comprobación del funcionamineto
Assert.AreEqual("ticketType", conversationData.response.cardIdResponse);
}
}
}

这是我要测试的类的代码(我只留下了失败的代码行)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using MyProgramVIP.Bots.Interactor.Services;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Utils;

namespace MyProgramVIP.Bots.Presenter
{
public class TicketPresenter
{
private static ILogger _logger = UtilsVIP.ApplicationLogging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

/// <summary>
/// Función getPutTicketMessage: encargada de comenzar con el flujo de poner un ticket.
/// </summary>
/// <param name="conversationData"></param>
public static void getPutTicketMessage(ConversationData conversationData)
{
try
{
//Here it crash.
_logger.LogInformation("INIT getPutTicketMessage");

//Code..........

//Never gets here.
_logger.LogInformation("ENDED getPutTicketMessage");
}
catch (Exception ex)
{
//Here it crash too.
_logger.LogError("EXCEPTION getPutTicketMessage" + ex.ToString());
}
}
}

这是错误所在的帮助类的代码:

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Model.Elements;

namespace MyProgramVIP.Bots.Utils
{
public class UtilsVIP
{
private static ILogger _logger = ApplicationLogging.CreateLogger("ILogger");

//Other funtions...

public static class ApplicationLogging
{
public static ILoggerFactory LoggerFactory { get; set; }
public static ILogger CreateLogger<T>() => LoggerFactory.CreateLogger<T>();
//Here LoggerFactory is null.
public static ILogger CreateLogger(string categoryName) => LoggerFactory.CreateLogger("VIPLog: " + categoryName);

}

//Other funtions...
}
}

就在它运行的行上:

LoggerFactory.CreateLogger("VIPLog: " + categoryName);

LoggerFactory 为空。

我在互联网上做了很多研究,但这一切都导致了非静态类信息。

如果它很重要,它是一个 Botframework 项目。

如有任何帮助,我们将不胜感激。

提前致谢。

最佳答案

非常感谢@ChetanRanpariya 的评论,我的问题的答案非常简单:

using NUnit.Framework;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Moq;
using System;
using MyProgramVIP.Bots.Presenter;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Utils;

namespace MyProgramVIPTest
{
public class TestsExample
{
[SetUp]
public void Setup() {

}

[Test]
public void TestExample1()
{
//Mocks
var mockLogger = new Mock<ILogger<TicketPresenter>>();
mockLogger.Setup(
m => m.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.IsAny<object>(),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()));

var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(() => mockLogger.Object);

//Just add this, I guess is replacing the objet with the mock.
UtilsVIP.ApplicationLogging.LoggerFactory = mockLoggerFactory.Object;

//Construción del modelo necesario para la prueba
ConversationData conversationData = new ConversationData();
conversationData.ticket = new Ticket();
conversationData.response = new Response();

//Invocación del método a probar
TicketPresenter.getPutTicketMessage(conversationData);

//Comprobación del funcionamineto
Assert.AreEqual("ticketType", conversationData.response.cardIdResponse);
}
}
}

只需添加以下内容:

UtilsVIP.ApplicationLogging.LoggerFactory = mockLoggerFactory.Object;

感谢您的帮助。

关于c# - C# 中使用 ILogger 进行单元测试静态方法 ILoggerFactory 为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63574805/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com