我只是新单元测试和ASP.NET MVC。我一直在试图用Steve Sanderson的“Pro ASP.NET MVC框架”让我的头脑同时进入。在这本书中有这样一段代码:Moq中的Verify()有多可靠?
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(产品)”;“如:
...
productsRepository.SaveProduct(product);
productsRepository.DeleteProduct(product);
...
测试通过(即纵容灾难性[催眠+智能感知诱导的错字:))
可这测试写入更好?或者有什么我应该知道的?非常感谢。
是的。一些模拟框架支持严格的模拟,这将验证模拟上没有其他方法被调用,但这些方法往往导致脆弱的测试。 – TrueWill 2010-04-09 22:19:50