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);
    }
szpic
  • 4,346
  • 15
  • 54
  • 85
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – nvoigt Mar 13 '14 at 08:50

2 Answers2

1

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

UnitOfWork unitOfWork=new UnitOfWork();
Aftab Ahmed
  • 1,727
  • 11
  • 15
  • 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` – szpic Mar 13 '14 at 08:44
  • 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. – Aftab Ahmed Mar 13 '14 at 08:51
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.

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61