我收到如下错误:
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);
}
答案 0 :(得分:1)
我认为您的对象unitOfWork
为null尝试创建此对象的实例
UnitOfWork unitOfWork=new UnitOfWork();
答案 1 :(得分:1)
检查此行的对象和属性:
Storage storage = unitOfWork.storageRepository.GetByID(id.Value);
您确定unitOfWork
是否已正确初始化?那么storageRepository
呢?使用调试器检查它们,在此行上设置断点。