在下面的代码中为什么mockTest.ToString()返回Null?
编辑:在示例代码中添加注释以显示如何解决问题。
Public Sub Main()
Try
Dim test = New TestClass
If test.ToString <> "stackoverflow rules" Then
Throw New Exception("Real Failed: Actual value: <" + test.ToString + ">")
End If
Dim mock = New Moq.Mock(Of TestClass)()
mock.SetupGet(Function(m As TestClass) m.Name).Returns("mock value")
' As per Mark's accepted answer this is the missing line of
' of code to make the code work.
' mock.CallBase = True
Dim mockTest = DirectCast(mock.Object, TestClass)
If mockTest.ToString() <> "mock value" Then
Throw New Exception("Mock Failed: Actual value: <" + mockTest.ToString + ">")
End If
Console.WriteLine("All tests passed.")
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine(ex.ToString)
Console.ForegroundColor = ConsoleColor.White
End Try
Console.WriteLine()
Console.WriteLine("Finished!")
Console.ReadKey()
End Sub
Public Class TestClass
Public Sub New()
End Sub
Public Overridable ReadOnly Property Name() As String
Get
Return "stackoverflow rules"
End Get
End Property
Public Overrides Function ToString() As String
Return Me.Name
End Function
End Class
TestClass 上的 Name 属性和 ToString 方法都是虚拟/可重写的,这意味着 Moq 将模拟它们。
默认情况下,Moq 对于具有引用类型返回类型的成员返回 null,除非您明确告诉它返回其他内容。由于字符串是引用类型,因此它返回 null。
您可以通过将 CallBase 设置为 true 来修复此问题。
如果您没有明确定义覆盖,将 CallBase 设置为 true 将导致 Moq 调用基本实现:
mock.CallBase = True
在这种情况下,这将指示模拟使用 ToString 的基本实现,因为不存在显式安装(因此调用 Name 属性,该属性does有一个设置)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)