【发布时间】:2014-06-20 03:11:26
【问题描述】:
我正在尝试运行我的测试,但是我得到一个“对象引用未设置为对象的实例”。有什么想法吗?我正在使用起订量。
测试方法:
// Arrange
Mock<ICustomerRepository> CustomerRepo = new Mock<ICustomerRepository>();
Customer NewCustomer = new Customert() { ID = 123456789, Date = DateTime.Now };
CustomerRepo.Setup(x => x.Add()).Returns(NewCustomer);
var Controller = new CustomerController(CustomerRepo.Object, new Mock<IProductRepository>().Object);
// Act
IHttpActionResult actionResult = Controller.CreateCustomer();
CreateCustomer 方法:
Customer NewCustomer = CustomerRepository.Add();
//ERROR OCCURS BELOW
return Created(Request.RequestUri + "/" + NewCustomer.ID.ToString(), new { customerID = NewCustomer.ID });
【问题讨论】:
-
调试时,哪个对象为空?您是否设置了 Request 对象?
-
creatcustomer 方法中的 NewCustomer 对象填充了 testmethod 中设置的 ID 和日期
-
如果您在调试模式下运行测试,NewCustomer 和 Request 不为空?使用 Moq 时,您需要配置 HttpContext,包括您的 Request 对象。
-
NewCustomer 不为空,请求为空
标签: c# unit-testing moq asp.net-web-api2