使用IExceptionFilter集成测试FilterAttribute

时间:2015-09-16 11:52:15

标签: c# unit-testing asp.net-mvc-5 .net-4.5 custom-attributes

我正在使用.Net 4.5C#MVC 5网站。

我正在尝试编写一个测试,以查看是否应该触发应该记录错误的FilterAttribute的机制。

属性:

public class LogErrorsAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext != null && filterContext.Exception != null)
        {
            var area = filterContext.RouteData.DataTokens["area"] as string;
            var controller = filterContext.RouteData.Values["controller"].ToString();
            var action = filterContext.RouteData.Values["action"].ToString();
            var httpMethod = filterContext.HttpContext.Request.HttpMethod;
            var loggerName = string.Format("Area - {0}, {1}Controller.{2} method {3}", string.IsNullOrWhiteSpace(area) ? "none" : area, controller, action, httpMethod);
            var model = filterContext.Controller != null && filterContext.Controller.TempData!= null ? filterContext.Controller.TempData["model"] : null;
            //log here
            MvcApplication.Logger.Error(new ErrorLogEntry {Error = filterContext.Exception, Summary = loggerName, Data = model });
        }
    }

我很难让OnException从模拟的上下文中解雇

测试

[TestFixture]
public class ControllerTest
{
    [Test]
    public void TestCompleteControllerErrorLoggingSystem()
    {
        var httpCtxStub = new Mock<HttpContextBase>();
        var controller = new CompleteController();
        var controllerCtx = new ControllerContext
        {
            Controller = controller,
            RequestContext = new RequestContext(httpCtxStub.Object, new RouteData())
        };

        controllerCtx.HttpContext = httpCtxStub.Object;

        controller.ControllerContext = controllerCtx; 
        var sessionId = Guid.NewGuid();
        controller.LeafManagerConfirmation(6868, 99M, "sdfsdfs", sessionId.ToString(), "Will", "CN");

    }
}

正在测试的控制器部分:

    public async void LeafManagerConfirmation(int leafTransId, decimal amount, string paymentReference, string sessionId, string productType, string cn)
    {
        //Update the Journey
        using (var db = new OnlineLegal())
        {
            var completedTransaction = db.Journey.SingleOrDefault(o => o.BarclaysTransactionRef == paymentReference);
            if (completedTransaction != null)
            {
                throw new InvalidOperationException(string.Format("Duplicate transaction recorded: leafId {0}, amount {1}, paymentReference {2}",
                    leafTransId, amount, paymentReference));
            }
    }

我传递的引用确实存在于数据库中,所以它始终触发InvalidOperationException并且测试在此之前是好的,但OnException中的FilterAttribute不会被触发(错误只是获取“从测试中看,吞下了”,我猜测它是因为HttpContextBase被模拟的上下文。

如果我对此是正确的,如何更改HttpContextBase模拟以便OnException点击LogErrorsAttribute

如果不是因为HttpContextBase我哪里出错?

0 个答案:

没有答案