Moq中Verify()的可靠性如何?

May*_*nde 4 asp.net-mvc unit-testing moq mocking verify

我只是单元测试和ASP.NET MVC的新手.我一直在尝试使用Steve Sanderson的"Pro ASP.NET MVC框架".书中有这段代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

他如此测试:

[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"]);
}
Run Code Online (Sandbox Code Playgroud)

测试通行证.

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

            ...
       productsRepository.SaveProduct(product);
       productsRepository.DeleteProduct(product);
            ...
Run Code Online (Sandbox Code Playgroud)

测试通行证(即宽恕一种灾难性的[催眠+智能感知 - 诱导的错字:))

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

Nic*_*ray 7

我想你可能会误解.Verify()方法的目的.

它验证是否使用期望值调用给定方法.

在本书的第187页,Steve说' 注意它是如何使用Moqs .Verify()方法来确保AdminController确实使用正确的参数调用DeleteProduct()."

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

正如TDD在本书的过程中被追随的那样

productsRepository.DeleteProduct(product);
Run Code Online (Sandbox Code Playgroud)

应首先加入测试

// 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"]);
Run Code Online (Sandbox Code Playgroud)

然后添加到代码中

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

     ...
productsRepository.SaveProduct(product);
productsRepository.DeleteProduct(product);
    ...
Run Code Online (Sandbox Code Playgroud)