unit testing - MOQ returning null. [mock concrete class method] -
unit testing - MOQ returning null. [mock concrete class method] -
[using moq]
i trying mock concrete class , mock virtual method "get()" of class. when testing method "getitemsnotnull()" returned null, instead of homecoming of mocked function.
here code
//someclasses.cs namespace moqexamples { public abstract class entity { } public class abc : entity { } public interface irepository<t> t : entity { iqueryable<t> get(); } public class repository<t> : irepository<t> t : entity { private readonly isession _session; public repository() { _session = null; } public repository(isession session) { _session = session; } protected isession currentsession { { homecoming _session; } } public virtual iqueryable<t> get() { homecoming currentsession.query<t>(); } } public interface iabcrepository { abc getitemsnotnull(); } public class abcrepository : repository<abc>, iabcrepository { public abc getitemsnotnull() { homecoming get().firstordefault(abc => abc !=null); } } }
and here test class
namespace moqexamples { [testfixture] public class someclassestest { private readonly mock<abcrepository> _abcrepositorymock = new mock<abcrepository>(mockbehavior.strict) { callbase = true }; [setup] public void setuptest() { _abcrepositorymock.setup(x => x.get()).returns(get); } public iqueryable<abc> get() { homecoming (new list<abc>() { new abc() }) iqueryable<abc>; } [test] public void testgetitemsnotnull() { assert.isnotnull(_abcrepositorymock.object.getitemsnotnull()); } } }
the assert alays fails..instead of returning someclassestest.get()
thanks advance guys!
i suspect problem:
return (new list<abc>() { new abc() }) iqueryable<abc>;
list<t>
doesn't implement iqueryable<t>
, always homecoming null. phone call asqueryable
convert instead:
return new list<abc>().asqueryable();
as aside, reason prefer casts on as
in situations: if you'd cast iqueryable<abc>
, you'd have received exception @ line causing problem. should utilize as
when it's not bug conversion "fail". as
operator should almost always followed nullity test.
(note behaviour in has nil mocking or moq. it's behaviour of as
operator...)
unit-testing generics inheritance mocking moq
Comments
Post a Comment