c# - How to mock OwinContext.Request.Query -
i trying unit test method checks query in owincontext.request.query
, alters it
public static async task setupquery(iowincontext context, iclientstore clientconfig) { // clientid querystring var clientidqs = context.request.query.where(x => x.key == constants.authorizerequest.clientid).select(x => x.value).firstordefault(); // more code here }
i using moq mock context. how mock query
object of type ireadablestringcollection
if take closer @ ireadablestringcollection
, see inherits ienumerable<keyvaluepair<string,string[]>
. other class/interface know inherits similar. idictionary<tkey,tvalue>
.
so set out find way mock ienumerable<keyvaluepair<string,string[]>
. take @ following extension method
public static class mockqueryableextensions { /// <summary> /// converts generic <seealso cref="system.collections.generic.ienumerable<t>"/> <see cref="moq.mock"/> implementation of quarable list /// </summary> public static mock<t> asquaryablemock<t, titem>(this mock<t> quaryablemock, ienumerable<titem> list) t : class,ienumerable<titem> { var queryablelist = list.asqueryable(); quaryablemock.as<iqueryable<titem>>().setup(x => x.provider).returns(queryablelist.provider); quaryablemock.as<iqueryable<titem>>().setup(x => x.expression).returns(queryablelist.expression); quaryablemock.as<iqueryable<titem>>().setup(x => x.elementtype).returns(queryablelist.elementtype); quaryablemock.as<iqueryable<titem>>().setup(x => x.getenumerator()).returns(queryablelist.getenumerator()); return quaryablemock; } }
with done left make sure create fake data, store in dictionary , set on mock of ireadablestringcollection
[testclass] public class owincontexttests { [testmethod] public void mock_owincontext_request_query_should_be_queryable() { //arrange var collection = new dictionary<string, string[]>() { {"a", new[]{"1", "2", "3"} }, {"b", new[]{"4", "5", "6"} } }; //applying extension method var querymock = new mock<ireadablestringcollection>().asquaryablemock(collection); var requestmock = mock.create<iowinrequest>(); requestmock.setup(m => m.query).returns(querymock.object); var contextmock = mock.create<iowincontext>(); contextmock.setup(m => m.request).returns(requestmock.object); var key = "b"; var expected = collection[key]; //act var actual = setupquery(contextmock.object, key); //assert assert.isnotnull(actual); collectionassert.areequal(expected, actual); } public static string[] setupquery(iowincontext context, string key) { // values querystring var values = context.request.query.where(x => x.key == key).select(x => x.value).firstordefault(); return values; } }
the above test passes linq query called on context request query works fake data provided.
Comments
Post a Comment