我想寫一些攔截器的單元測試,攔截器攔截基類(實現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