我想写一些拦截器的单元测试,拦截器拦截基类(实现ILoggable)。
可记录基类没有可调用的方法,仅用于由日志工具初始化。
据我了解我应该:如何单元测试拦截器?
- 模拟的ILoggable和ILogger
- 初始化日志工具
- 注册就可以了我的拦截
- 调用嘲笑ILoggable的一些方法
问题是我的接口没有方法调用,因此没有任何东西会被拦截。
在这里采取行动的正确方法是什么?
我应该嘲笑ILoggable手动并添加存根方法调用?
另外,我是否应该嘲笑容器?
我正在使用Moq和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
}
我测试拦截器的实现。我想检查它做它应该做什么。如果您建议使用属性来拦截可记录的方法,那么我不明白记录工具存在的原因。查看代码以了解测试的内容。 – 2011-04-27 11:47:34