NSubstitute ILogger .NET Core

Nic*_*aro 5 .net c# unit-testing nsubstitute .net-core

我正在尝试围绕我的异常处理编写单元测试,以便我可以验证我的记录器是否正确记录了异常.我使用NSubstitute作为模拟框架,Microsoft.Extensions.Logging.ILogger我必须遵循我的测试:

[Fact]
public void LogsExcpetionWhenErrorOccursInCreate()
{
   var newUser = new UserDataModel
   {
      FirstName = "Rick",
      MiddleName = "Jason",
      LastName = "Grimes",
      Email = "rick.grimes@thedead.com",
      Created = new DateTime(2007, 8, 15)
   };
   var exception = new Exception("Test Exception");
   // configure InsertOne to throw a generic excpetion
   _mongoContext.InsertOne(newUser).Returns(x => { throw exception; });

   try
   {
      _collection.Create(newUser);
   }
   catch
   {
      // validate that the logger logs the exception as an error
      _logger.Received().LogError(exception.Message);
   }
}
Run Code Online (Sandbox Code Playgroud)

使用以下方法测试日志记录:

public UserDataModel Create(UserDataModel user)
{
     try
     {
          return MongoContext.InsertOne(user);                
     }
     catch(Exception e)
     {
           _logger?.LogError(e.Message);
           throw new DataAccessException("An error occurred while attempting to create a user.", e);
      }
Run Code Online (Sandbox Code Playgroud)

}

我的测试失败,出现以下错误:

Message: NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
    Log<Object>(Error, 0, Test Exception, <null>, Func<Object, Exception, String>)
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
    Log<Object>(Error, 0, *Test Exception*, <null>, Func<Object, Exception, String>)
Run Code Online (Sandbox Code Playgroud)

我不确定为什么这会失败,因为即使在错误消息中,调用也是一样的.

提前致谢!

更新:

这是测试的构造函数,这是我注入logger mock的地方:

public UserCollectionTest()
{
   _mongoContext = Substitute.For<IMongoContext<UserDataModel>>();
   _logger = Substitute.For<ILogger>();
   // create UserCollection with our mock client
   _collection = new UserCollection(_mongoContext, _logger);
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*ard 21

看起来接受的答案在 .NET Core 3 或 .NET 5 中不起作用。

这是在github问题中找到的解决方法

创建一个新的 MockLogger 类

public abstract class MockLogger : ILogger
{
    void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) => 
        Log(logLevel, formatter(state, exception));

    public abstract void Log(LogLevel logLevel, string message);

    public virtual bool IsEnabled(LogLevel logLevel) => true;

    public abstract IDisposable BeginScope<TState>(TState state);
}
Run Code Online (Sandbox Code Playgroud)

用新的模拟记录器替换您的模拟记录器

// Old 
// var logger = Substitute.For<ILogger>();
// New
var logger = Substitute.For<MockLogger>();
Run Code Online (Sandbox Code Playgroud)

使用新记录器检查通话

logger.Received().Log(LogLevel.Error, Arg.Is<string>(s => s.Contains("some log message")));
Run Code Online (Sandbox Code Playgroud)

要与泛型一起使用ILogger<T>,只需将类更改为

logger.Received().Log(LogLevel.Error, Arg.Is<string>(s => s.Contains("some log message")));
Run Code Online (Sandbox Code Playgroud)


Val*_*rii 11

LogError不是ILogger方法,因此当您尝试检查此方法是否使用某些参数调用时,NSubstitute会尝试以某种方式处理它(我不知道具体如何)并失败.

LogError扩展方法的代码是:

public static void LogError(this ILogger logger, string message, params object[] args)
{
  if (logger == null)
    throw new ArgumentNullException("logger");
  logger.Log<object>(LogLevel.Error, (EventId) 0, (object) new FormattedLogValues(message, args), (Exception) null, LoggerExtensions._messageFormatter);
}
Run Code Online (Sandbox Code Playgroud)

因此,您必须检查是否已调用Log方法.

我简化了你的例子.我认为这个想法应该是明确的.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var logger = Substitute.For<ILogger>();
        try
        {
            Create(logger);
        }
        catch
        {
            logger.CheckErrorMessage("My Message");
        }
    }

    public string Create(ILogger logger)
    {
        try
        {
            throw new Exception("My Message");
        }
        catch (Exception e)
        {
            logger?.LogError(e.Message);
            throw new Exception("An error occurred while attempting to create a user.", e);
        }
    }
}

public static class TestExtensions
{
    public static void CheckErrorMessage(this ILogger logger, string message)
    {
        logger.Received().Log(
            LogLevel.Error,
            Arg.Any<EventId>(),
            Arg.Is<object>(o => o.ToString() == message),
            null,
            Arg.Any<Func<object, Exception, string>>());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @AndreSoares 看起来这个解决方案在较新版本的 .NET 中不再有效,而在发布答案时该版本还不存在。https://github.com/nsubstitute/NSubstitute/issues/597 (5认同)
  • 不适合我。它根本不匹配。 (4认同)