在下面的代码中为什么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
Run Code Online (Sandbox Code Playgroud)
TestClass上的Name属性和ToString方法都是虚拟/可覆盖的,这意味着Moq将模拟它们.
默认情况下,Moq为具有引用类型返回类型的成员返回null,除非您明确告诉它返回其他内容.由于字符串是引用类型,因此返回null.
您可以通过将CallBase设置为true来修复它.
如果您没有明确定义覆盖,则将CallBase设置为true将导致Moq调用基本实现:
mock.CallBase = True
Run Code Online (Sandbox Code Playgroud)
在这种情况下,这将指示,因为没有eplicit设置存在使用的ToString基实现(因此调用名称属性,它模拟确实有设置).