C# 单元测试Db连接期间出现NullReferenceException

C# 单元测试Db连接期间出现NullReferenceException,c#,entity-framework,unit-testing,C#,Entity Framework,Unit Testing,我得到的错误如下所示: 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. 此方法中会引发此错误: public ActionResult Details(int? id)

我得到的错误如下所示:

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.
此方法中会引发此错误:

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);
    }
在这方面:

Storage storage = unitOfWork.storageRepository.GetByID(id.Value);
Storage storage = unitOfWork.storageRepository.GetByID(id.Value);
下面是我的单元测试代码:

[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));
}
我试着调试这个测试,所有的值都正确通过了。在db中有一条Id为1的记录

这个代码有什么问题

@使用测试初始化更新:

 [TestInitialize]
    public void Initialize()
    {
        Mock<IUnitOfWork> mock = new Mock<IUnitOfWork>();
        fakeRepo = mock.Object;
        SC = new StorageController(fakeRepo);
    }
[测试初始化]
公共无效初始化()
{
Mock Mock=新Mock();
fakeRepo=mock.Object;
SC=新的StorageController(fakeRepo);
}

我认为您的对象
unitOfWork
为空。请尝试创建此对象的实例

UnitOfWork unitOfWork=new UnitOfWork();

检查此行的对象和属性:

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

您确定
unitOfWork
已正确初始化吗?那么
storageRepository
呢?使用调试器检查这两个代码,并在此行设置断点。

我更新了代码。工作单位没问题。当我通过
Id=null
时,一切都正常,我得到了我想要的并断言通过。问题在于
Id=null
尝试确保storageRepository的值不是null。我怀疑当您传递带有某个值的id时,storageRepository引发了一些异常,并反过来返回null。可能是的重复项