c# - unit testing generic method with moq -
i have generic method returns list of records table:
public list<t> getvalidrecords<t>() t: class, igetlistoftables { try { return _context.set<t>().where(x => x.valid == 1).tolist(); } catch (exception ex) { throw new exception(ex.message); } }
and have unit test method:
[testmethod] public void getvalidrecords() { var data = new list<tablename> { new tablename() {valid= 1}, new tablename() {valid= 1} }.asqueryable(); var mockset = new mock<dbset<tablename>>(); mockset.as<iqueryable<tablename>>().setup(m => m.provider).returns(data.provider); mockset.as<iqueryable<tablename>>().setup(m => m.expression).returns(data.expression); mockset.as<iqueryable<tablename>>().setup(m => m.elementtype).returns(data.elementtype); mockset.as<iqueryable<tablename>>().setup(m => m.getenumerator()).returns(data.getenumerator()); var mockcontext = new mock<almonentitiesnew>(); mockcontext.setup(x => x.tablename).returns(mockset.object); var database = new database(mockcontext.object); var numberofrecords = database.getvalidrecords<tablename>(); assert.areequal(2, numberofrecords.count, "wrong number of valid records."); }
the problem actual number of records table, , not moqed number. how can fix it?
you need dependencies on ef implementation out of getvalidrecords method, particularly _context otherwise ef specific implementation going bleed unit tests. in order test getvalidrecords unit need make able stand on it's own. if want test suggest using integration test, retrieving records db , asserting came ok - not require use of mocking framework, , ok way test functionality.
on topic of making getvalidrecords stand alone, see dbset implements ienumerable, maybe want this:
public static list<t> getvalidrecords<t>(this ienumerable<t> source) t: class, igetlistoftables { if (null == source) { throw new argumentnullexception("source"); } return source.where(x => x.valid == 1).tolist(); }
Comments
Post a Comment