我有以下(遗留的,从前辈继承的)VB.Net(框架 2.0)类和方法,它们在异常时创建系统事件日志:
Public Interface IMyClass
Function MyMethod(ByVal aValue As String) As Date
End Interface
Public Class MyClass
Implements IMyClass
Public Function MyMethod(ByVal aValue As String) As Date Implements IMyClass.MyMethod
Try
' Calculate return date based on aValue
Catch ex As Exception
Call MyUtilityClass.LogError("MyClass", "MyMethod", ex)
Throw
End Try
End Function
End Class
Partial Public NotInheritable Class MyUtilityClass
Public Shared Sub LogError(ByVal className As String,
ByVal methodName As String,
ByVal ex As Exception)
' Write details to Event Log
End Sub
End Class
我正在尝试在 C#(框架 4.5)单元测试项目中对此进行测试,部分逻辑要求 aValue
是用逗号分隔的两个数字 - 从而引发异常和事件日志如果没有。
我已经设置了以下单元测试以确保正确抛出异常:
[TestClass]
public class MyClassUnitTest
{
private readonly StubMyClass myClass = new StubMyClass();
[TestMethod]
[ExpectedException(typeof(InvalidCastException))]
public void TestMyMethodInvalidMissingNumber()
{
this.myClass.MyMethod("0,");
}
}
这一切都很好地工作并且测试通过了,因为 MyMethod
中的逻辑导致了预期的异常。但是,我不希望写入事件日志。那么,我该如何对 MyUtitlityClass
进行填充以拦截对 LogError
的调用而不是什么都不做?
我看到的所有 Fakes 示例都是针对返回假值的方法(全部 是用 C# 编写的!)当我尝试实现这样的模式时,它给出了 LogError 做的错误没有 setter/getter 。
最佳答案
我认为您正在寻找以下内容:
Using context = ShimsContext.Create()
ShimMyUtilityClass.LogStringStringException =
Sub(aClass As String, aMethod As String, anException As Exception)
// YOUR CODE HERE
End Sub
End Using
或者,在 C# 中:
using (context = ShimsContext.Create()) {
ShimMyUtilityClass.LogStringStringException =
(string aClass, string aMethod, Exception anException) => {
// YOUR CODE HERE
};
}
关于c# - Shim 一个 void 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17836683/