c# - How to write a moq test to setup a method to return a count value -
in controller action, whenever new product added check in database product no not present already. code check looks like
public actionresult index(productmodel model) { var productcount = _productsservice.getall(true).count(x => x.productnumber == model.productnumber); if (productcount > 0) modelstate.addmodelerror("productnumber", product present in system!"); // more processing }
i m new moq testing , trying write unit test setup getall method return 0. have written not seem work
var _productsservice = new mock<iproductsservice>(); _productsservice.setup(m => m.getall(true).count()).returns(0);
any ideas? thanks
this not how use moq -- count
not method (it's linq/other 3rd party), don't mock it. need mock getall
method, method on mockable dependency. "tell" getall
return product model matching parameter, so:
[test] public void index_reportsmodelerror_whenproductalreadyexists() { const int existingproductnumber = 10; var _productsservice = new mock<iproductsservice>(); var existingproduct = new product { productnumber = existingproductnumber }; _productsservice.setup(m => m.getall(true)).returns(new [] { existingproduct }); controller.index(new productmodel { productnumber = existingproductnumber }); // assert }
fixing existing tests simple making sure getall
never returns products number same 1 in index
parameter:
const int existingproductnumber = 10; const int newproductnumber = 20; var _productsservice = new mock<iproductsservice>(); var existingproduct = new product { productnumber = existingproductnumber }; _productsservice.setup(m => m.getall(true)).returns(new [] { existingproduct }); controller.index(new productmodel { productnumber = newproductnumber }); // assert
Comments
Post a Comment