0

I'm getting error like below:

An exception of type 'System.NullReferenceException' occurred in magazyn.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

This error is thrown in this method:

public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Storage storage = unitOfWork.storageRepository.GetByID(id.Value);
        if (storage == null)
        {
            return HttpNotFound();
        }
        return PartialView(storage);
    }

in this line:

Storage storage = unitOfWork.storageRepository.GetByID(id.Value);

Here my unit Test code:

[TestMethod]
public void Details()
{
    int? a = null;
    var result = SC.Details(a);
    Assert.IsInstanceOfType(result, typeof(HttpStatusCodeResult));
    var code = result as HttpStatusCodeResult;
    Assert.AreEqual((int)HttpStatusCode.BadRequest, code.StatusCode);
    a = 1;
    result = SC.Details(a);
    Assert.IsInstanceOfType(result, typeof(HttpNotFoundResult));
}

I tried debugging this test and all values are passed correctly. In db there is a record with Id=1 What is wrong with this code?

@Update with Test initialization:

 [TestInitialize]
    public void Initialize()
    {
        Mock<IUnitOfWork> mock = new Mock<IUnitOfWork>();
        fakeRepo = mock.Object;
        SC = new StorageController(fakeRepo);
    }
1

2 Answers 2

1

Check the objects and properties of this line:

Storage storage = unitOfWork.storageRepository.GetByID(id.Value);

Are you sure that unitOfWork is correctly initialized? What about storageRepository? Check both of them with the debugger, setting a breakpoint on this line.

Sign up to request clarification or add additional context in comments.

Comments

1

I think Your Object unitOfWork is null try to create an instance of this object

UnitOfWork unitOfWork=new UnitOfWork();

2 Comments

I updated my code. UnitOfwork is OK. When I pass Id=null everything is ok and I get what I want and Assert pass. Problem is with Id!=null
try to make sure storageRepository has value other than null. i suspect when you pass id with some value storageRepository is throwing some exception and in turn it returns null.

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.