Niknak
Niknak

Reputation: 593

System.ArgumentNullException : Value cannot be null in unit test - C#

I'm getting this error when I run the unit test: Error Message: System.ArgumentNullException : Value cannot be null. Parameter name: logger and also I'm getting this warning: Field 'OrderControllerTest._logger' is never assigned to, and will always have its default value null

Is there a way to silence the logger or test it?

Still new to programming and eager to learn. Have struggled with this for a long time. Appreciate your help and guidance.

Update with stack trace

Stack Trace:
   at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)
   at Microsoft.Extensions.Logging.LoggerExtensions.LogError(ILogger logger, Exception exception, String message, Object[] args)
   at Project.Controllers.OrderController.CustomerOrders(String customerId) in C:\projects\Project\Controllers\OrderController.cs:line 34
   at Tests.OrderControllerTest.AllOrdersForCustomer() in C:\projects\UnitTests\Project.Service.Tests\OrderControllerTest.cs:line 74

What I have so far:

OrderControllerTest.cs:

using System;
using System.Collections.Generic;
using NUnit.Framework;
using Project.Models;
using Project.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Tests
{
  [TestFixture]
  public class OrderControllerTest
  {
      ILogger<OrderController> _logger;

      public OrderControllerTest()
      {

      }

      [Test]
      public void AllOrdersForCustomer()
      {
        // Arrange
        var controller  = new OrderController(_logger);
        var expectedResult = new List<Order>();
        var oneOrder = new Order()
        {
            orderId = 228, 
            product= "Jeans",
            status = "Ready for shipping",
            price= 20$
        };

        var twoOrder = new Order()
        {
            caseId = 512, 
            creditorName = "Basketball",
            status = "Shipped",
            totalOpenBalance = 30$
        };
        expectedResult.Add(oneOrder);
        expectedResult.Add(twoOrder);

        // Act
        var actionResult = controller.CustomerOrders("1243");
        var result = (List<Order>)actionResult;

        // Assert
        for (var i = 0; i < result.Count; i++)
        {               
          CollectionAssert.AreEqual(expectedResult, result);
        }
    }
}

OrderController.cs:

using System;
using System.Collections.Generic;
using Project.Models;
using Project.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;


namespace Project.Controllers
{
  public class OrderController : Controller
  {
    ILogger<OrderController> _logger;

    public OrderController(ILogger<OrderController> logger)
    {
        _logger = logger;
    }

    [HttpGet("customers/{customerId}/orders")]
    public List<Order> CustomerOrders(string customerId)
    {
        try
        {
            return OrderRepository.AllOrders(customerId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Cant retrieve no orders.");
            return null;
        }
    }
  }
}

 ILogger<OrderController> _logger;

 public OrderControllerTest()
 {
    _logger = new Mock<ILogger<OrderController>>().Object;  
 }

OrderRepository.cs:

    public static List<Order> AllOrders(string customerId)
    {
        var orderlist = new List<Order>();


        if (Order!=null && Order.Count>0)
        {
            if (Order.TryGetValue(customerId, out orderlist))
                return orderlist;
        }
        return FromDB(customerId);

    }

Upvotes: 6

Views: 15946

Answers (2)

Phil Golding
Phil Golding

Reputation: 471

Assuming you have taken input from EL MOJO, you need to initialise your ILogger in your tests, using Moq:

Mock<ILogger<OrderController>> _logger;

public OrderControllerTest()
{
    _logger = new Mock<ILogger<OrderController>>();
    _logger.Setup(m => m.LogError(It.IsAny<Exception>(), It.IsAny<string>()));
}

Now you should initialise your controller with the following:

var controller  = new OrderController(_logger.Object);

Upvotes: 4

EL MOJO
EL MOJO

Reputation: 793

In the constructor for your "OrderControllerTest" class, you need to create a mock of the ILogger interface. The Logger is a dependency of your OrderController and you don't want to test its functionality within a unit test for your controller.

There are many good mocking frameworks out there. I prefer Moq but there are many others. You would then need to mock the methods that your OrderController is utilizing.

Moq Example:

using ...
using Moq;

namespace Tests
{
  [TestFixture]
  public class OrderControllerTest
  {
    public OrderControllerTest()
    {
      var mockLogger = new Mock<ILogger<OrderController>>();
      mockLogger.Setup( x => x.LogError( It.IsAny<Exception>(), It.IsAny<string>() );
      _logger = mockLogger.Object;
    }
  ...
  }
}

Upvotes: 1

Related Questions