gpt4 book ai didi

asp.net-mvc - 起订量中的验证()有多可靠?

转载 作者:行者123 更新时间:2023-12-04 22:16:54 24 4
gpt4 key购买 nike

我只是单元测试和 ASP.NET MVC 的新手。我一直在尝试使用 Steve Sanderson 的“Pro ASP.NET MVC Framework”来深入了解这两者。书中有一段代码:

public class AdminController : Controller
{
...

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
...
productsRepository.SaveProduct(product);

TempData["message"] = product.Name + " has been saved.";
return RedirectToAction("Index");
}
}

他像这样测试:
[Test]
public void Edit_Action_Saves_Product_To_Repository_And_Redirects_To_Index()
{
// Arrange
AdminController controller = new AdminController(mockRepos.Object);

Product newProduct = new Product();

// Act
var result = (RedirectToRouteResult)controller.Edit(newProduct, null);

// Assert: Saved product to repository and redirected
mockRepos.Verify(x => x.SaveProduct(newProduct));
Assert.AreEqual("Index", result.RouteValues["action"]);
}

测试通过。

所以我故意通过添加“productsRepository.DeleteProduct(product);”来破坏代码。在“SaveProduct(product);”之后如:
            ...
productsRepository.SaveProduct(product);
productsRepository.DeleteProduct(product);
...

测试通过。(即宽恕一个灾难性的 [催眠 + 智能感知] 引起的错字:))

这个测试可以写得更好吗?或者有什么我应该知道的吗?非常感谢。

最佳答案

我认为您可能误解了 .Verify() 方法的目的。

它验证给定的方法是用预期的值调用的。

在这本书的第 187 页上,Steve 说“注意它如何使用 Moqs .Verify() 方法来确保 AdminController 确实使用正确的参数调用了 DeleteProduct()。”

因此,在您的情况下,测试通过,因为它只是验证调用而不是功能。

由于在本书的过程中遵循 TDD,因此添加了

productsRepository.DeleteProduct(product);

应该首先添加到测试中
// Assert: Saved product to repository, then deleted and redirected
mockRepos.Verify(x => x.SaveProduct(newProduct))
mockRepos.Verify(x => x.DeleteProduct(newProduct));
Assert.AreEqual("Index", result.RouteValues["action"]);

然后添加到代码中
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product product, HttpPostedFileBase image)
{

...
productsRepository.SaveProduct(product);
productsRepository.DeleteProduct(product);
...

关于asp.net-mvc - 起订量中的验证()有多可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2598499/

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