2

I refactor my web api functions (to take advantage of web api 2 changes) but can't figure out how to refactor my xUnit tests testing for 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 this (return type changed to IHttpActionResult, and 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 do I test:

  • for a correct header? Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  • for a specific string in the custom exception message? Assert.Equal("Token expired.", response.ContentString());
mortenma71
  • 1,078
  • 2
  • 9
  • 27
  • What kind of response does an exception generate? Just cast the response to that (for example OkNegotiatedContentResult for HTTP 200) – Jeroen Vannevel Jul 17 '15 at 22:45

1 Answers1

2

I was looking at this answer: How do I unit test web api action method when it returns IHttpActionResult?

However, return Ok("Request received"); returns OkNegotiatedContentResult and not OkResult as suggested.

So this:

Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("Token expired", response.ContentString())

I changed into this:

Assert.IsType<OkNegotiatedContentResult<string>>(response);
Assert.Equal(((OkNegotiatedContentResult<string>)response).Content, "Token expired");
Community
  • 1
  • 1
mortenma71
  • 1,078
  • 2
  • 9
  • 27