Hi everyone I am new to testing so please go easy :). I'm having trouble testing my api controllers. I have created a separate class to test the controller but I having issues with 'Object reference not set to valid instance'
The api controller and method I want to test:
namespace Project.Controllers.Api
{
[Authorize]
[Route("/api/entries/{date}")]
public class EntryController : Controller
{
private ILogger<EntryController> _logger;
private ITrackerRepository _repository;
public EntryController(ITrackerRepository repository, ILogger<EntryController> logger)
{
_repository = repository;
_logger = logger;
}
[HttpGet("")]
public JsonResult Get(string date)
{
// DateTime date mm/dd/yyyy
DateTime dateTime = Convert.ToDateTime(date);
var result = Mapper.Map<IEnumerable<EntryViewModel>>(_repository.GetDiaryEntries(dateTime, User.Identity.Name));
if (result != null)
{
return Json(result);
}
else
{
return Json(null);
}
}
}
my attempt to unit test with xunit:
namespace test.Project.UnitTests
{
public class EntryControllerTest
{
public EntryControllerTest()
{
}
[Fact]
public void TestInvalidViewModels()
{
// Created test mock/empty repository
TestProjectRepository testRepo = new TestProjectRepository();
var controller = new EntryController(testRepo, null);
var result = controller.Get("01/12/1899");
Assert.Equal(result, null);
}
}
}
I get the issue that 'Object reference is not set to an instance of an object" in the Controller.cs file. Any help much appreciated, thank you.
Userdefined for the controller to access and there is a call toUser.Identity.Name, so that might be the culprit. Provided the OP did not exclude any other important details.