开发者

Unit-testing model changes in Asp.net MVC 3

开发者 https://www.devze.com 2023-02-06 19:50 出处:网络
I have a ProductController class and a Product model. Ev开发者_如何学Cerytime the Create action in the ProductController is called, it creates a new Product based on FormCollection and then it calls a

I have a ProductController class and a Product model. Ev开发者_如何学Cerytime the Create action in the ProductController is called, it creates a new Product based on FormCollection and then it calls a function inside Product to change a date:

[HttpPost]
public ActionResult Create(FormCollection form)
{
    Product product = new Product();
    TryUpdateModel(product, form);

    if(ModelState.IsValid)
    {
        product.ChangeDate(form["date"]);
        repository.SaveProduct(product);

        return RedirectToAction("Index");
    }
    else
        return View();
}

I was wondering how I can test Product so I know .ChangeDate is being called (via Moq's Verify). I did not use the Asp.Net automatic model-binding because I want to catch any binding exception via TryUpdateModel. I am not sure if i should put .ChangeDate in the Controller or Repository class. I am using Moq, MVC3, and Entity Framework 4. Any help is appreciated!

Thanks, Alex


You can setup an expectation on the SaveProduct method of the mocked repository so that it is called with a specific argument. This specific argument will be the product which is constructed inside the controller action. Then you can assert that the Date property of this object is the same as the one you passed as argument in the Create action in the form collection.

var mock = new Mock<IRepository>();
mock.Setup(
    x => x.SaveProduct(
        It.Is<Product>(p => p.Date == someExpectedDate)
    )
);
0

精彩评论

暂无评论...
验证码 换一张
取 消