c# - Unit Testing using Moq -
this method under controller used create dummy keys encrypt data in application , store same in amazon s3 bucket.
public jsonresult savemasterkeys(string mektext, int thismek) { string foldername = string.empty, filename = string.empty; list<string> foldernamelist = new list<string>(); foldernamelist.add("guard1"); foldernamelist.add("guard2"); try { if (thismek == 1) { foldername = "guard1"; filename = "newmek1.key"; } else { foldername = "guard2"; filename = "newmek2.key"; } awss3file aws = new awss3file(); //aws.bucketexist(filepath); //aws.createfile(mektext, filepath); // check weather folder exist or not if (!aws.checkfolderexist(foldername)) { foreach (var item in foldernamelist) { aws.createfolder(item); if (item == "guard1") { aws.createfileintos3((item == foldername ? mektext : ""), item, "newmek1.key"); aws.createfileintos3("", item, "mek1.key"); } else { aws.createfileintos3((item == foldername ? mektext : ""), item, "newmek2.key"); aws.createfileintos3("", item, "mek2.key"); } } } else { aws.createfileintos3(mektext, foldername, filename); } viewdata["savemessage"] = "saved successfully."; } catch (exception ex) { xtp.logger.logcritical("xtp.web.internaltools", ex.tostring()); viewdata["savemessage"] = "keys not updated successfully."; } return json(new { success = true, value = viewdata["savemessage"] }, jsonrequestbehavior.allowget); }
and testmethod have written same
[testmethod] public void mockalways() { var mock = new mock<accountcontroller>(); jsonresult json = new jsonresult(); //new { success = true, value = viewdata["savemessage"] }, jsonrequestbehavior.allowget json.data = new { success = true, value = "sa" }; json.jsonrequestbehavior = jsonrequestbehavior.allowget; mock.setup(x => x.savemasterkeys("ss", 1)).returns(json); var controller = new accountcontroller(); var result = controller.savemasterkeys("ss", 1) jsonresult; assert.areequal(mock.object.savemasterkeys("ssxs", 1), result.data.tostring()); }
i getting invalid setup error. there way resolve error?
i think misunderstood how mock controller's action. mocking , comparing mocked controller. not way go(it checking whether true == true
.
basically error means moq cannot override non-virtual member(it self-explanatory). should change method's signature virtual
allow overriding it.
but - shouldn't mock action this. instead should mock dependencies(services, contexts, gateways etc.) , check whether known input values can expected results without mocking action itself.
Comments
Post a Comment