我想为拦截Loggable基类(实现ILoggable)的拦截器编写一些单元测试。Loggable
基类没有可调用
的方法,它仅用于由日志记录工具初始化。
据我了解,我应该:
- 模拟ILoggable和ILogger
- 初始化日志记录工具
- 在上面注册我的拦截器
- 调用模拟的ILoggable的一些方法
问题是我的ILoggable接口没有可调用的方法,因此不会截获任何内容。
什么是在这里采取行动的正确方式?
我应该手动模拟ILoggable并添加一个存根方法来调用吗?
另外,我也应该嘲笑容器吗?
我正在使用起订量和 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
}