c# - Mocks; assigning delegates using Moq -
currently
i'm using moq
create handful of mock objects; far working nicely. 'assign' delegate using moq i'm doing
var somemock = new mock<isomeinterface>(); somemock.setup(x => x.dosomething(it.isany<int>())).returns(this.dosomething)
where this.dosomething
method accepting int
parameter; fundamentally it's same construction x.dosomething
on isomeinterface
.
is possible assign delegate, without neeed specifying of parameters, i.e. not using it.isany<int>()
? ideally this:
var somemock = new mock<isomeinterface>(); somemock.setup(x => x.dosomething).returns(this.dosomething)
no, that's not possible. that's not "shortcoming" of moq - c# doesn't back upwards it.
some background:
let's assume isomeinterface
declared follows:
public interface isomeinterface { void foo(int a, int b); }
that mean parameter of setup
method have func<isomeinterface, action<int, int>>
. problem setup
method have defined in generic way, because method have type of parameters:
setup<t1, t2>(func<t, action<t1, t2>> param)
t
generic type mock class, t1
, t2
parameters of method.
calling method result in compiler error:
the type arguments method mock.setup<t1, t2>(system.func<userquery.isomeinterface,system.action<t1,t2>>)
cannot inferred usage. seek specifying type arguments explicitly.
to create work, need phone call this:
somemock.setup<int, int>(x => x.dosomething)
or this:
somemock.setup(x => (action<int, int>)x.dosomething);
in both cases, have specify type of parameters, already.
as why compiler error:
x.dosomething
method group. there exists implicit conversion action<int, int>
. however, implicit conversion executed, compiler needs know types of t1
, t2
. types can inferred after conversion took place. 2 steps depend on each other , that's why doesn't work.
c# unit-testing mocking moq
No comments:
Post a Comment