c# - Xunit test IHttpActionResult web api 2 function for custom message -


i refactor web api functions (to take advantage of web api 2 changes) can't figure out how refactor xunit tests testing custom exception messages.

i refactor this:

[route("resetpassword"), httppost] public httpresponsemessage resetpassword([frombody] resetpasswordrequest request) {   try   {     var resetpermission = _userpasswordresetrequestrepository.getbytoken(request.token);      if (resetpermission.expires < datetimeoffset.now)       throw new exception("token expired");      _userpasswordrepository.setpassword(resetpermission.userid, request.password);      return request.createresponse(httpstatuscode.ok, "request received");   }   catch (exception ex)   {     return request.createresponse(httpstatuscode.internalservererror, ex.message);   } } 

to (return type changed ihttpactionresult, , return statements changed):

[route("resetpassword"), httppost] public ihttpactionresult resetpassword([frombody] resetpasswordrequest request) {   try   {     var resetpermission = _userpasswordresetrequestrepository.getbytoken(request.token);      if (resetpermission.expires < datetimeoffset.now)       throw new exception("token expired");      _userpasswordrepository.setpassword(resetpermission.userid, request.password);      return ok("request received");   }   catch (exception ex)   {     return internalservererror(ex);   } } 

my failing xunit test:

[theory] [inlinedata(-10, true)] [inlinedata(10, false)] public void iftokenexpired_shouldreturnerror(int expireoffsetminutes, bool shouldbeexpired) {   ...   // assert   assert.equal(httpstatuscode.ok, response.statuscode); // <-- fail   if (shouldbeexpired)     assert.equal("token expired.", response.contentstring()); // <-- fail } 

how test:

  • for correct header? assert.equal(httpstatuscode.ok, response.statuscode);
  • for specific string in custom exception message? assert.equal("token expired.", response.contentstring());

i looking @ answer: how unit test web api action method when returns ihttpactionresult?

however, return ok("request received"); returns oknegotiatedcontentresult , not okresult suggested.

so this:

assert.equal(httpstatuscode.ok, response.statuscode); assert.equal("token expired", response.contentstring()) 

i changed this:

assert.istype<oknegotiatedcontentresult<string>>(response); assert.equal(((oknegotiatedcontentresult<string>)response).content, "token expired"); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -