gpt4 book ai didi

c# - 使用 MStest 和最小起订量测试 TryUpdateModel()

转载 作者:行者123 更新时间:2023-11-30 14:40:39 25 4
gpt4 key购买 nike

我目前正在尝试测试使用 TryUpdateModel() 的插入方法。我正在伪造所需的 controllercontext,虽然它有效但似乎没有发布我设置的模型。

这是我正在测试的方法:

 [AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _SaveAjaxEditing(int? id)
{
if (id == null)
{
Product product = new Product();
if (TryUpdateModel(product))
{
//The model is valid - insert the product.
productsRepository.Insert(product);// AddToProducts(product);
}
}
else
{
var recordToUpdate = productsRepository.Products.First(m => m.ProductID == id);
TryUpdateModel(recordToUpdate);
}
productsRepository.Save();
return View(new GridModel(productsRepository.Products.ToList()));
}

这是我当前的测试:

        [TestMethod]
public void HomeControllerInsert_ValidProduct_CallsInsertForProducts()
{
//Arrange
InitaliseRepository();

var httpContext = CustomMockHelpers.FakeHttpContext();
var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
//controller.ControllerContext = new ControllerContext();

var request = Mock.Get(controller.Request);
request.Setup(r => r.Form).Returns(delegate()
{
var prod = new NameValueCollection
{
{"ProductID", "9999"},
{"Name", "Product Test"},
{"Price", "1234"},
{"SubCatID", "2"}
};
return prod;
});


// Act: ... when the user tries to delete that product
controller._SaveAjaxEditing(null);
//Assert
_mockProductsRepository.Verify(x => x.Insert(It.IsAny<Product>()));
}

正在调用该方法,但当它到达 TryUpdateModel() 时,它似乎无法拾取发布的对象。任何关于我哪里出错的指示都会很棒。

最佳答案

已排序。似乎完全 mock Httpcontext 有点矫枉过正。

controller.ControllerContext = new ControllerContext();

var prod = new FormCollection
{
{"ProductID", "1"},
{"Name", "Product Test"},
{"Price", "1234"},
{"SubCatID", "2"}
};

controller.ValueProvider = prod.ToValueProvider();

这就是诀窍。现已发布。

关于c# - 使用 MStest 和最小起订量测试 TryUpdateModel(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5077059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com