0

I have an N-tier project that am trying to test the API controller but the flow is a little bit more complex which makes me ask for some opinion from you guys... Please any suggestion will be appreciated so much...

I'm getting an error

Object reference not Set to An Instance Of An Object

This is my test class and method that get all fake symptoms

[TestClass]
public class SymptomsControllerTest 
{

    private Mock<IAdministrationManagementService> _administrationManagementServiceMock;
    SymptomsController objController;
    IList<SymptomObject> listSymptoms;

    [TestInitialize]
    public void Initialize()
    {
        _administrationManagementServiceMock = new Mock<IAdministrationManagementService>();
        objController = new SymptomsController(_administrationManagementServiceMock.Object);

        listSymptoms = new List<SymptomObject>() {
         new SymptomObject() { Name = "Head1" },
         new SymptomObject() { Name = "Head2" },
         new SymptomObject() { Name = "Head3" }
        };
    }

    [TestMethod]
    public void Symptom_Get_All()
    {
        //Arrange
        _administrationManagementServiceMock.Setup(x => x.GetSymptoms()).ReturnsAsync(listSymptoms);

        //Act
        var result = objController.Get() as List<SymptomObject>;

        //Assert
        Assert.AreEqual(result.Count, 3);
        Assert.AreEqual("Head1", result[0].Name);
        Assert.AreEqual("Head2", result[1].Name);
        Assert.AreEqual("Head3", result[2].Name);

    }

}

the service am trying to communicate to looks likes this

 public Task<IList<SymptomObject>> GetSymptoms()
    {
        return Task.Run(() =>
        {
            try
            {
                using (var _uow = new HomasUoW())
                {
                    var entities = _uow.Symptoms.GetAll().Where(x => x.isDelete == false);

                    if (entities.Count() > 0)
                    {
                        IList<SymptomObject> list = new List<SymptomObject>();
                        foreach (var entity in entities)
                        {
                            var obj = AutoMapper.Mapper.DynamicMap<Symptom, SymptomObject>(entity);

                            obj.Name = entity.Name;

                            list.Add(obj);


                        }

                        return list;
                    }
                    else
                    {
                        throw new InvalidOperationException(Resources.NonExistingObjectRetrievalError);
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
        });

    }

and the API Controller looks like this

 public IHttpActionResult Get()
    {
        try
        {
            var symptoms = _Service.GetSymptoms();

            if (symptoms != null)
            {
                return Ok(symptoms);
            }

            return NotFound();
        }
        catch (Exception ex)
        {

            return InternalServerError(ex);
        }
    }

Please look at it carefully and check if am missing any thing that is not allowing the test to pass.

5
  • Am thing if the problem is from the Mapping inside the services Commented Apr 14, 2015 at 10:40
  • Which object is null? Commented Apr 14, 2015 at 10:42
  • that is what I cant really detect since i can't use Break Point on test Commented Apr 14, 2015 at 10:44
  • Why can't you debug your tests? That sounds like a more significant problem to solve first. Using a debugger should be the first step in diagnosing a problem. Commented Apr 14, 2015 at 10:45
  • the null exception is coming from this line of code Assert.AreEqual(result.Count, 3); Commented Apr 14, 2015 at 10:50

1 Answer 1

1

Based on your comment:

the null exception is coming from this line of code Assert.AreEqual(result.Count, 3);

Clearly the result object is null. Look at how you get that object:

var result = objController.Get() as List<SymptomObject>;

Even if Get() returns something, the behavior of the as keyword is such that when you try to interpret an object as the wrong type, the result will be null. You're trying to interpret that object as List<SymptomObject>. But what does Get() return?

public IHttpActionResult Get()

You can't cast IHttpActionResult to List<SymptomObject>. You have two options:

  1. Your WebAPI controller should return a List<SymptomObject> (which I would say is probably the better approach, but there are more considerations to be made outside the scope of the code shown), or;
  2. Your test should validate the IHttpActionResult being returned.
Sign up to request clarification or add additional context in comments.

3 Comments

To be precisE: it should return an OkResult<Task<IList<SymptomObject>>>. I don't see why you would advocate for the first solution thou'gh, since IHttpActionResult is so handy
@JeroenVannevel: For re-use and unit testing, returning the actual type of resource being returned is pretty handy too. Perhaps we've encountered different issues in solving different problems, but just returning the model itself has worked really well for me.
No doubt that having the actual type is useful of course, but that is also contained in the IHttpActionResult. It's simply wrapped in a response that also indicates the result of the call (Ok<T>, BadRequest<T>, etc). But sure, both are valid approaches of course.

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.