【发布时间】:2018-09-20 09:46:22
【问题描述】:
我有两个班级:
-
ProductController类与SingleProduct动作 -
Helper类有自己的方法getProduct(ProductsContext db, string id)从数据库中检索指定的产品
我正在尝试使用 Moq 框架为 SingleProduct 操作创建单元测试。
我正在为Helper 对象创建模拟,但是当测试运行时,我收到NullReferenceException 模拟Helper 对象。
我做错了什么?
[TestMethod]
public void ProductNotFoundTest()
{
var mockHelper = new Mock<Helper>();
mockHelper.Setup(h => h.getProduct(It.IsAny<ProductsContext>(), It.IsAny<string>())).Returns(It.IsAny<Product>());
ProductController controller = new ProductController(mockHelper.Object);
ViewResult result = controller.SingleProduct("i'm not exist") as ViewResult;
Assert.AreEqual("~/Views/Product/ProductNotFound.cshtml", result.ViewName);
}
namespace OnlineStoreParser.Controllers
{
public class ProductController : Controller
{
private Helper _h;
public ProductController(Helper h)
{
Helper _h = h;
}
public ProductController()
{
_h = new Helper();
}
public ActionResult SingleProduct(string id)
{
Product product;
using (var context = new ProductsContext())
{
// Find product with specified ID
product = _h.getProduct(context, id);
if(product != null)
{
ViewBag.History = product.History;
ViewBag.Images = product.Photos;
return View(product);
}
else
{
return View("~/Views/Product/ProductNotFound.cshtml");
}
}
}
}
}
namespace OnlineStoreParser.Models
{
public class Helper
{
public Helper() { }
public virtual Product getProduct(ProductsContext db, string id)
{
return db.Products.SingleOrDefault(p => p.ProductId == id);
}
}
}
【问题讨论】:
-
在产品控制器中,我看到 ProductsContext 没有模拟对象,这可能是原因吗?
-
据我了解,我在 ProductController 构造函数中创建此对象并将其分配给 ProductController 的字段 - _h 。然后在 SingleProduct 操作中,我调用该对象的 getProduct() 方法。如果我错了,请纠正我
-
只需按照与
Helper相同的方式进行操作即可:) 您必须像使用第一个构造函数一样通过构造函数设置所有要模拟的类。跨度> -
很好,我不是在谈论辅助对象。我说的是您在控制器的 SingleProduct 方法中传递给 _helper 对象的 ProductsContext 对象。那是空的。
-
同意@MightyBadaboom 你需要在控制器中模拟 ProductsContext 对象
标签: c# asp.net-mvc unit-testing moq