John Doe
John Doe

Reputation: 215

Object not set to reference while unit testing API controller (asp.net 5, xunit)

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.

Upvotes: 3

Views: 3301

Answers (1)

Nkosi
Nkosi

Reputation: 247283

From your code, this User.Identity.Name is your most likely reason for the error.

[Fact]
public void TestInvalidViewModels()
{
    //Arrange        
    var username = "[email protected]";
    var identity = new GenericIdentity(username, "");
    var fakeUser = new GenericPrincipal(identity, roles: new string[] { });

    TestProjectRepository testRepo = new TestProjectRepository();
    var controller = new EntryController(testRepo, null);
    controller.User = fakeUser;
    //Act
    var result = controller.Get("01/12/1899");
    //Assert
    Assert.Equal(result, null);
}

Upvotes: 2

Related Questions