3

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.

2
  • 1
    Which line in the controller is throwing the NullReference Exception? Perhaps it has something to do with the logger; it is being passed in as 'null' when you create the EntryController from the test. Commented Apr 25, 2016 at 17:12
  • @denvercoder9 I would have guessed the logger as well, but noticed that it was not being used in the example shown. No where in the test setup was a User defined for the controller to access and there is a call to User.Identity.Name, so that might be the culprit. Provided the OP did not exclude any other important details. Commented Apr 25, 2016 at 18:17

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You were right, the identity was causing the issue. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.