3
내 로거가 예외를 올바르게 로깅하고 있는지 확인할 수 있도록 예외 처리와 관련된 단위 테스트를 작성하려고합니다.NS 대체 ILogger .NET 코어
[Fact]
public void LogsExcpetionWhenErrorOccursInCreate()
{
var newUser = new UserDataModel
{
FirstName = "Rick",
MiddleName = "Jason",
LastName = "Grimes",
Email = "[email protected]",
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);
}
}
는 다음과 같은 방법 로깅 테스트 할 : 나는 내 테스트는 다음을 가지고 조롱 프레임 워크와 Microsoft.Extensions.Logging.ILogger
로 NSubstitute을 사용하고
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);
}
을}
내 테스트 실패 다음 오류 :
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>)
왜 이것이 실패하는지 잘 모르겠습니다. 왜냐하면 심지어 오류 메시지에서도 호출이 동일하기 때문입니다.
미리 감사드립니다.
public UserCollectionTest()
{
_mongoContext = Substitute.For<IMongoContext<UserDataModel>>();
_logger = Substitute.For<ILogger>();
// create UserCollection with our mock client
_collection = new UserCollection(_mongoContext, _logger);
}
ILogger 대체품을 만들고 주입하는 방법을 명확히하십시오. –
테스트 생성자가있는 게시물을 업데이트했습니다. 여기에서 하위를 삽입하고 있습니다. –