gpt4 book ai didi

unit-testing - 如何对拦截器进行单元测试?

转载 作者:行者123 更新时间:2023-12-04 04:21:12 31 4
gpt4 key购买 nike

我想为拦截 的拦截器编写一些单元测试。可记录 基类(实现 ILoggable )。
可记录 基类没有可调用的方法,它仅用于由日志记录工具初始化。
据我了解,我应该:

  • 模拟 ILoggable ILogger
  • 初始化日志工具
  • 在上面注册我的拦截器
  • 调用模拟 的一些方法ILoggable

  • 问题是我的 ILoggable 接口(interface)没有可调用的方法,因此不会截获任何内容。
    什么是在这里采取行动的正确方式?
    我应该 mock ILoggable 手动并添加一个 stub 方法来调用?
    另外,我也应该 mock 容器吗?

    我正在使用起订量和 NUnit。
    编辑:
    这是我的拦截器实现供引用:
    public class LoggingWithDebugInterceptor : IInterceptor
    {
    #region IInterceptor Members

    public void Intercept(IInvocation invocation)
    {
    var invocationLogMessage = new InvocationLogMessage(invocation);

    ILoggable loggable = invocation.InvocationTarget as ILoggable;

    if (loggable == null)
    throw new InterceptionFailureException(invocation, string.Format("Class {0} does not implement ILoggable.", invocationLogMessage.InvocationSource));

    loggable.Logger.DebugFormat("Method {0} called with arguments {1}", invocationLogMessage.InvokedMethod, invocationLogMessage.Arguments);

    Stopwatch stopwatch = new Stopwatch();
    try
    {
    stopwatch.Start();
    invocation.Proceed();
    stopwatch.Stop();
    }
    catch (Exception e)
    {
    loggable.Logger.ErrorFormat(e, "An exception occured in {0} while calling method {1} with arguments {2}", invocationLogMessage.InvocationSource, invocationLogMessage.InvokedMethod, invocationLogMessage.Arguments);
    throw;
    }
    finally
    {
    loggable.Logger.DebugFormat("Method {0} returned with value {1} and took exactly {2} to run.", invocationLogMessage.InvokedMethod, invocation.ReturnValue, stopwatch.Elapsed);
    }
    }

    #endregion IInterceptor Members
    }

    最佳答案

    如果只是拦截器使用 Logger你类的属性(property)为什么比那里有呢?你也可以把它放在拦截器上。 (就像 Ayende 在他的 post here 中解释的那样)。

    除此之外 - 拦截器只是一个与接口(interface)交互的类 - 一切都是高度可测试的。

    关于unit-testing - 如何对拦截器进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5803233/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com