[英]Unit Testing error “Object reference not set to an instance of an object.”
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);
}
And here is the test method 这是测试方法
[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));
}
It throws an error saying 它抛出一个错误说
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
I'm using RhinoMock as mocking tool. 我正在使用RhinoMock作为模拟工具。 Can someone help with what mistake i'm making?
有人可以帮我解决我犯的错误吗?
After stubbing the method use Return
to indicate what should it return, for example: 在对方法进行存根后,使用
Return
来指示它应该返回什么,例如:
_mockRepository
.Stub(x => x.GetModuleKindPropertyNames(Arg<string>.Is.Anything))
.Return(Enumerable.Empty<string>().AsQueryable());
Also, change this line: 另外,更改此行:
_controller.GetModulePropertyName(Arg<string>.Is.Anything);
to this: 对此:
_controller.GetModulePropertyName(string.Empty);
As the exception explains - Arg
is only to be used in mock definitions. 正如例外所述 -
Arg
仅用于模拟定义。
You don't have a return on your stub. 你的存根上没有回报。
_mockRepository.Stub(x => x.GetModuleKindPropertyNames(Arg<string>.Is.Anything));
without that return, this line will be running a lambda against a null reference 如果没有返回,此行将针对空引用运行lambda
IList<Property> model = temp.Select(item => new Property {Name = item}).ToList();
so: 所以:
_mockRepository.Stub(x => x.GetModuleKindPropertyNames(Arg<string>.Is.Anything)).Return(new Module[]{}); // set some return data here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.