Last active
January 1, 2019 09:03
-
-
Save hatelove/6abf3896fc5b7af1d3bc4e7810b0c60e to your computer and use it in GitHub Desktop.
ExceptionFilter 單元測試 sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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