c# - Moq function call with expression -
i have following interface used di , ioc webservice clients
public interface iwcfserviceclientprovider <tcontract>: idisposable tcontract: class { tresult execute<tresult>(expression<func<tcontract, tresult>> expression); tresult execute<tresult>(expression<func<tcontract, tresult>> expression, bool closeconnection = true); void execute(expression<action<tcontract>> expression); void execute(expression<action<tcontract>> expression, bool closeconnection = true); }
in test class have following:
list<baselookup> mylist = new list<baselookup> { new baselookup { id =1, code = "1001"}, new baselookup { id =2, code = "1002"}, new baselookup { id =3, code = "1003"}};
in test method
mock<iwcfserviceclientprovider<ilookupservice>> lookupserviceclinetprovider = new mock<iwcfserviceclientprovider<ilookupservice>>(); var controller = new electorsearchcontroller(lookupserviceclinetprovider.object); lookupserviceclinetprovider.setup(mock => mock.execute(lookup => lookup.getlist(10))).returns(mylist).verifiable(); var list = controller.testmethod(); lookupserviceclinetprovider.verifyall();
list have value when parameter getlist
set 10 i.e getlist(10)
not getlist(i)
i=10
the following works
lookupserviceclinetprovider.setup(mock => mock.execute(it.isany<expression<func<ilookupservice, list<baselookup>>>>(), true )).returns((list<baselookup>)mylist).verifiable();
but want mock call getlist
, not call execute. if works, can filter values in return
method
as interim solution wrote simple brute-force solution compare expressions following:
public static bool expressionmatcher<tin, tresult>(expression<func<tin, tresult>> expr1, expression<func<tin, tresult>> expr2) { if (expr1 == null || expr2 == null) { return false; } if (expr1 == expr2) { return true; } if (expr1.type != expr2.type) { return false; } if (expr1.body == expr2.body) { return true; } if (expr1.body.nodetype != expr2.body.nodetype) { return false; } if (expr1.body.nodetype == expressiontype.call) { dynamic expr1body = expr1.body; dynamic expr2body = expr2.body; if (expr1body.method.name == expr2body.method.name && expr1body.method.returntype == expr2body.method.returntype) { if (expr1body.arguments == null && expr2body.arguments == null) { return true; } if (expr1body.arguments.count != expr2body.arguments.count) { return false; } return true; } } return false; }
i used following call it
expression<func<ilookupservice, list<baselookup>>> expr = lookup => lookup.getmylist(it.isany<long>()); .setup(mock => mock.execute(it.is<expression<func<ilookupservice, list<baselookup>>>>(method => expressionmatcher(method, expr)))) .returns(mylist) .verifiable();
i don't need check arguments' type @ point. if have better answer, please let me know
Comments
Post a Comment