2014-02-28 136 views
1

我正在使用Moq框架在一个vb.net项目中进行测试。VB.net Moq公共共享函数

我现在的情况是我想测试一个函数,它内部有一个来自另一个类的“公共共享函数”调用,我喜欢moq这个调用。 的情况类似于

'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 

的事情是,我可以起订量的数据库调用来获得我想要的数据,因为不是一个共享对象 但我喜欢做的起订量CommonData.GetTotal避免一切内部执行 有没有办法做到这一点?

回答

2

你不能直接用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 

所以,你会在生产和ICommonData在单元测试模拟使用RealCommonData


或者,反过来想:

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._commonDataRealCommonData一个实例,并在单元测试中一个模拟。

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

+0

感谢Dominic,这是我的想法,我更喜欢不使用这个接口,因为我在整个应用程序中使用了这个类,它很容易访问而不需要实例化。 也许我可以改变成单身模式来混合使用这两种方法。 谢谢 – ajimenez

+0

你当然可以换个角度:将共享函数的代码放入一个实现了接口的非共享类/函数中,让共享函数在该接口上工作(并将实例存储将在共享领域工作)。然后,您可以保留使用共享函数的代码。 – sloth

+0

查看我的编辑例子。 – sloth