我有以下(继承自前辈的) VB.Net (Framework2.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# (Framework4.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的调用而不做任何事情呢?
我看到的所有假示例都是用于返回假值的方法(并且都是用C#编写的!)当我尝试实现这样的模式时,它会给出一个错误,即LogError没有一个getter。
发布于 2013-07-24 14:58:58
我想你是在寻找这样的东西:
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
};
}发布于 2013-07-24 15:01:03
首先,您需要创建包含MyUtilityClass的程序集的伪造程序集。然后,使用MyUtility类的shimmed实例模拟LogError方法。以下措施可能会有所帮助:
using (ShimsContext.Create())
{
ShimMyUtilityClass temp = new ShimMyUtilityClass();
temp.LogStringStringException = ....
this.myClass.MyMethod("0,");
}https://stackoverflow.com/questions/17836683
复制相似问题