asp.net mvc - Testing a method in MVC which makes calls to Repositories -
i have mvc method so:
public actionresult changestatus(string productid, string statustochange) { var producttochangestatus = _updateproductrepository.getupdateproduct(productid); if (statustochange.tolower() == changestatusto.disable) { producttochangestatus.active = "false"; } else { producttochangestatus.active = "true"; } _updateproductsmanager.upsertproduct(producttochangestatus); return json(new { success = true }); }
this method gets existing product based on 'productid', changes 'active' property on based on 'statustochange' value, saves , returns json success.
the test setup so:
private productcontroller _controller; private mock<iupdateproductrepository> _iproductrepository; [testinitialize] public void testsetup() { _iproductrepository = new mock<iupdateproductrepository>(); _controller = new productcontroller(_iproductrepository.object); }
wrote test method so:
[testmethod] public void disable_a_product_which_is_currently_enabled() { const string productid = "123"; var productbeforestatuschange = new product() { active = "true", id = new guid().tostring(), name = "testproduct", productid = "123" }; var productafterstatuschange = new product() { active = "false", id = new guid().tostring(), name = "testproduct", productid = "123" }; _iproductrepository.setup(r => r.getupdateproduct(productid)).returns(productbeforestatuschange); _iproductrepository.setup(r => r.upsertproduct(productbeforestatuschange)).returns(productafterstatuschange); var res = _controller.changestatus("123", "disable") jsonresult; assert.areequal("{ success = true }", res.data.tostring()); }
the test fails error:
object reference not set instant of object.
on debugging found fails inside
if(...)
condition actual setting of active property happening. since productid that's being passed not real product object can't retrieved code work on.
i tried use mock think usage not correct.
so want know is, how test method method returns actionresult in turn calling repository work object(s).
thanks in advance.
you seems missing setup for
_updateproductsmanager.upsertproduct()
the way setup getupdateproduct
() method ought setup upsertproduct
() on mock instance.
Comments
Post a Comment