.net - 为什么 Moq 不运行重写的 ToString 方法?

标签 .net moq mocking

在下面的代码中为什么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 属性,该属性确实有一个安装程序)。

关于.net - 为什么 Moq 不运行重写的 ToString 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1998611/

相关文章:

java - Mockito When() 不起作用

c++ - 如何期待稍后创建的指针参数

c# - 在 DetailsView 中绑定(bind) DropDownList

C#、MAF、单独 AppDomain 中的未处理异常管理

c# - 使对象出列是否会从队列对象中删除引用并允许 GC?

c# - 如何在单元测试中使用 Moq 和 DbFunctions 来防止 NotSupportedException?

c# - 开放泛型类型的 CaSTLe Windsor Complex 注册

c# - 如何模拟构造函数内部的依赖关系?

c# - 在单元测试中模拟 SignalR Clients.Group 的方法

forms - 如何使用 Moq 模拟 MVC 表单 POST