c# - Unit test for a Web API method without any injected dependency -
i have method in web api project , since it's pretty simple , there no injected dependency , deals concrete posted object, i'm not sure how create unit test it. there in design of below code change make more test-friendly?
public class homecontroller : apicontroller { public httpresponsemessage post(rootobject root) { httpresponsemessage httpresponse; return trycreateresponse(root, out httpresponse) ? httpresponse : request.createerrorresponse(httpstatuscode.internalservererror, "an unhandled exception occurred on server."); } private bool trycreateresponse(rootobject root, out httpresponsemessage httpresponse) { var success = false; httpresponse = null; try { var creator = (modelstate.isvalid)? new okresponsecreator(root) ihttpresponsecreator: new badreqeuestresponsecreator(applicationsettings.httpbadrequesterrormessage); var abstracthttpresponse = new responsecontext(creator).createhttpresponse(); httpresponse = request.createresponse(abstracthttpresponse.statuscode, abstracthttpresponse); success = true; } catch { success = false; } return success; } }
start testing homecontroller.post
fake rootobject
, asserting expected result returned test.
although there no injected dependencies, method , extension class dependent on okresponsecreator
, badreqeuestresponsecreator
responsecontext
, applicationsettings
.
given extent of coupling of classes not obvious in example , dependencies, suggest start looking @ classes.
if initial test fails, can try cycle of refactoring , retesting make mentioned classes mockable can safely injected controller better testability.