System.ArgumentNullException : Value cannot be null. (Parameter 'logger')

Priya
Priya
Participant
936 Points
28 Posts

I'm using xUnit test for unit testing and trying to test the api endpoints. And for this I'm trying to mock the Logger and passing to the controller. But it's showing errors:

System.ArgumentNullException : Value cannot be null. (Parameter 'logger')

I tried two approaches but not able to success:

I) Using NullLoggerFactory

private readonly ILogger<TestController> _logger;

        public TestControllerTest()
        {
            _logger = new Logger<TestController>(new NullLoggerFactory());
            _controller = new TestController(_logger);
        }

II) Using Mock.Of

private readonly ILogger<TestController> _logger;

        public TestControllerTest()
        {
            _logger = Mock.Of<ILogger<TestController>>();
            _controller = new TestController(_logger);
        }

 

Views: 13014
Total Answered: 2
Total Marked As Answer: 1
Posted On: 21-Apr-2020 01:34

Share:   fb twitter linkedin
Answers
Smith
Smith
None
2568 Points
74 Posts
         

Try to use following:

private readonly Mock<ILogger<TestController>> _logger;

public TestControllerTest()
{
    _logger = new Mock<ILogger<TestController>>();
    _logger.Setup(m => m.LogError(It.IsAny<Exception>(), It.IsAny<string>()));
    _controller = new TestController(_logger.Object, _service);
    
}
Posted On: 21-Apr-2020 02:56
Thanks Smith. But it's not working to me.
 - Priya  21-Apr-2020 04:50
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

Please try following:

private readonly Mock<ILogger<TestController>> _logger;

public TestControllerTest()
{
    _logger = new Mock<ILogger<TestResultController>>();
    _controller = new TestController(_logger.Object, _service);
    
}
Posted On: 21-Apr-2020 04:54
Thanks. It works for me.
 - Priya  21-Apr-2020 05:00
 Log In to Chat