Skip to content

Instantly share code, notes, and snippets.

@hatelove
Last active January 1, 2019 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hatelove/6abf3896fc5b7af1d3bc4e7810b0c60e to your computer and use it in GitHub Desktop.
Save hatelove/6abf3896fc5b7af1d3bc4e7810b0c60e to your computer and use it in GitHub Desktop.
ExceptionFilter 單元測試 sample code
using static System.Web.Http.Hosting.HttpPropertyKeys;
namespace WebApplication1.CustomFilters.Tests
{
[TestClass()]
public class ApiExceptionFilterAttributeTests
{
private readonly ApiExceptionFilterAttribute _apiExceptionFilterAttribute = new ApiExceptionFilterAttribute();
private HttpActionExecutedContext _context;
[TestMethod()]
public void when_exception_happened()
{
_context = GivenContext(new ThirdPartyException());
WhenExceptionHappened();
ResponseContentShouldBe(new ApiResponse { ErrorCode = ResponseStatusCode.GeneralError });
}
private void WhenExceptionHappened()
{
_apiExceptionFilterAttribute.OnException(_context);
}
private void ResponseContentShouldBe(ApiResponse expected)
{
var actual = _context.Response.Content.ReadAsAsync<ApiResponse>().Result;
expected.ToExpectedObject().ShouldEqual(actual);
}
private HttpActionExecutedContext GivenContext(Exception exception)
{
return CreateExecutedContext(exception);
}
private HttpActionExecutedContext CreateExecutedContext(Exception exception)
{
return new HttpActionExecutedContext
{
ActionContext = new HttpActionContext
{
ControllerContext = new HttpControllerContext
{
Request = GetHttpRequestMessage()
}
},
Exception = exception,
Response = new HttpResponseMessage()
};
}
private HttpRequestMessage GetHttpRequestMessage()
{
var request = new HttpRequestMessage();
request.Properties[HttpConfigurationKey] = new HttpConfiguration();
return request;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment