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

时间:2014-03-13 08:37:54

标签: 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)
    {
        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);

这是我的单元测试代码:

[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的记录 这段代码有什么问题?

@Update with Test initialization:

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

2 个答案:

答案 0 :(得分:1)

我认为您的对象unitOfWork为null尝试创建此对象的实例

UnitOfWork unitOfWork=new UnitOfWork();

答案 1 :(得分:1)

检查此行的对象和属性:

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

您确定unitOfWork是否已正确初始化?那么storageRepository呢?使用调试器检查它们,在此行上设置断点。