【问题标题】:VB.net Moq Public Shared FunctionVB.net Moq 公共共享功能
【发布时间】:2014-02-28 10:03:13
【问题描述】:

我正在使用 Moq 框架在一个 vb.net 项目中进行测试。

我现在的情况是我想测试一个函数,该函数内部有一个从另一个类调用“公共共享函数”的函数,我喜欢最小起订量这个调用。 情况类似

'Sub in Main Class
Public Sub StartProcess()
    Dim total As Integer = CommonData.GetTotal()
    ...
End Sub

'Function in CommonData class
Public Shared Function GetTotal()
    ...
    Dim total As Integer = database.GetTotal()
    ...
    Return total
End Sub

问题是我可以最小化数据库调用来获取我想要的数据,因为它不是共享对象 但我喜欢做的是 moq CommonData.GetTotal 以避免所有内部执行 有什么办法吗?

【问题讨论】:

    标签: vb.net unit-testing tdd moq


    【解决方案1】:

    您不能直接使用 Moq 模拟共享函数(您必须使用可以实际模拟共享函数的 Typemock Isolator 或 Microsoft Fakes 等框架)。

    但是,您可以将对共享代码的调用隐藏在接口后面并模拟该接口的实现。

    Interface ICommonData
        Function GetTotal() As Integer
    End Interface
    
    Public Sub StartProcess(commonData As ICommonData)
        Dim total As Integer = commonData.GetTotal()
        ...
    End Sub
    
    Public Class RealCommonData
        Implements ICommonData
    
         ...calls your shared function...
    End Class
    

    因此,您将在生产中使用 RealCommonData,在单元测试中使用 ICommonData 的模拟。


    或者,反过来:

    Interface ICommonData
        Function GetTotal() As Integer
    End Interface
    
    Public Class RealCommonData
     Implements ICommonData
    
       Function GetTotal() As Integer Implements...
            Dim total As Integer = database.GetTotal()
            ...
            Return total
      End Function
    End Class
    
    Module CommonData
        Shared _commonData As ICommonData
    
        Public Shared Function GetTotal()
            Return _commonData.GetTotal()
        End Function
    End Module
    

    因此,在生产中,您可以将CommonData._commonData 设置为RealCommonData 的实例,并在单元测试中设置为模拟。

    这样,您可以像以前一样保持对CommonData.GetTotal() 的调用,而无需更改这部分代码(我听说有些人称之为静态网关模式或类似的东西)。

    【讨论】:

    • 谢谢 Dominic,这就是我的想法,我宁愿不使用这个接口,因为我在整个应用程序中都使用这个类,而且无需实例化即可轻松访问。也许我可以更改为单例模式以混合使用这两种方法。谢谢
    • 您当然可以反过来:将共享函数的代码放在实现接口的非共享类/函数中,并让您的共享函数只在该接口上工作(并且将您将处理的实例存储在共享字段中)。然后你可以保留使用共享函数的代码。
    猜你喜欢
    • 2013-05-23
    • 1970-01-01
    • 2015-01-25
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多