单元测试ExceptionFilterAttribute

时间:2015-02-03 14:37:46

标签: unit-testing c#-4.0 asp.net-web-api

我试图对我的异常过滤器代码进行单元测试。我可以验证异常,但我似乎无法在单元测试中找到要验证的异常消息。这是我的代码......

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is TimeoutException)
        {
            context.Response = context.Request.CreateErrorResponse(HttpStatusCode.RequestTimeout, context.Exception.Message);
            return;
        }
        if (context.Exception is UnauthorizedAccessException)
        {
            context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, context.Exception.Message);
            return;
        }

        context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to process your request.");
    }
}

单元测试代码

[Theory, MemberData("ExceptionData")]
    public void OnExceptionTests(Exception ex, HttpStatusCode statusCode)
    {
        var request = new HttpRequestMessage();
        var actionContext = InitializeActionContext(request);
        var httpActionExectuedContext = new HttpActionExecutedContext(actionContext, ex);

        var exceptionHandlingAttribute = new ExceptionHandlingAttribute();
        exceptionHandlingAttribute.OnException(httpActionExectuedContext);
        Assert.Equal(actionContext.Response.StatusCode, statusCode);
        Assert.Equal(actionContext.Response.ReasonPhrase, ex.Message);
    }

    public static IEnumerable<object[]> ExceptionData
    {
        get
        {

            return new[]
            {
                new object[] { new TimeoutException("My timeout message."), HttpStatusCode.RequestTimeout }                   
            };
        }
    }

我的问题是:Assert.Equal(actionContext.Response.ReasonPhrase,ex.Message);

当我尝试在观察窗口中查看它时,我似乎无法找到&#34;我的超时消息&#34;在回应中。

更新:

actionContext.Response.ReasonPhrase =&#34;请求超时&#34;

ex.Message =&#34;我的超时消息&#34;

1 个答案:

答案 0 :(得分:0)

CreateErrorResponse的消息部分不是属性,您必须阅读内容才能获取值。这就是我做的......

var responseContent = await actionContext.Response.Content.ReadAsStringAsync();

阅读后,responseContent现在有:

{ "message" : "My timeout message." }