MVC 4:单元测试误差"未将对象引用设置到对象的实例" [英] MVC 4 : Unit Testing error "Object reference not set to an instance of an object."
本文介绍了MVC 4:单元测试误差"未将对象引用设置到对象的实例"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的控制器我想测试控制器是否调用库方法。
下面是该方法的控制器
In my controller I want to test if the controller is calling the repository method. Here is the method in controller
[HttpGet]
public ActionResult GetModulePropertyName(string moduleTypeValue)
{
var temp = _modulerepository.GetModuleKindPropertyNames(moduleTypeValue);
IList<Property> model = temp
.Select(item => new Property {Name = item})
.ToList();
return PartialView("GetModulePropertyName",model);
}
这是在测试方法
[TestMethod]
public void GetModulePropertyName_Action_Calls_GetModuleKindPropertyNames()
{
_mockRepository.Stub(x => x.GetModuleKindPropertyNames(Arg<string>.Is.Anything));
_controller.GetModulePropertyName(Arg<string>.Is.Anything);
_mockRepository.AssertWasCalled(x=>x.GetModuleKindPropertyNames(Arg<string>.Is.Anything));
}
它抛出一个错误话说
Test method AdminPortal.Tests.ModuleControllerTests.GetModulePropertyName_Action_Calls_GetModuleKindPropertyNames threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Linq.Queryable.Select(IQueryable`1 source, Expression`1 selector)
at AdminPortal.Areas.Hardware.Controllers.ModuleController.GetModulePropertyName(String moduleTypeValue) in ModuleController.cs: line 83
at AdminPortal.Tests.ModuleControllerTests.GetModulePropertyName_Action_Calls_GetModuleKindPropertyNames() in ModuleControllerTests.cs: line 213
我使用的 RhinoMock 作为嘲讽的工具。
有人可以用我正在做什么错误帮助?
I'm using RhinoMock as mocking tool. Can someone help with what mistake i'm making?
推荐答案
存根方法使用返回,以表明我应该将其返回后,例如:
After stubbing the method use "Return" to indicate what should it return, for example:
_mockRepository
.Stub(x => x.GetModuleKindPropertyNames(Arg<string>.Is.Anything))
.Return(Enumerable.Empty<string>().AsQueryable());
另外,更改这一行:
Also, change this line:
_controller.GetModulePropertyName(Arg<string>.Is.Anything);
这样:
_controller.GetModulePropertyName(string.Empty);
作为例外解释 - 精氨酸仅在模拟的定义中使用
As the exception explains - Arg is only to be used in mock definitions.
这篇关于MVC 4:单元测试误差&QUOT;未将对象引用设置到对象的实例&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文