小编Nic*_*aro的帖子

NSubstitute ILogger .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 …
Run Code Online (Sandbox Code Playgroud)

.net c# unit-testing nsubstitute .net-core

5
推荐指数
2
解决办法
1789
查看次数

标签 统计

.net ×1

.net-core ×1

c# ×1

nsubstitute ×1

unit-testing ×1