Question

I'm doing test in one vb.net project using Moq framework.

The situation I have now is I want to test one function that have inside it one call to a 'Public Shared Function' from another class and I like to moq this call. The situation is similar to

'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

The thing is I can moq the database call to get data that I want because is not a shared object But what I like to do is moq CommonData.GetTotal to avoid all the internal execution Is there anyway to do that?

Was it helpful?

Solution

You can't mock a shared function directly with Moq (you'll have to use a framework like Typemock Isolator or Microsoft Fakes that can actually mock shared functions).

However, you can hide your calls to shared code behind an interface and mock the implementation of that interface.

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

So you would use RealCommonData in production and a mock of ICommonData in unit tests.


Or, the other way round:

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

So, in production you would set CommonData._commonData to an instance of RealCommonData, and to a mock in unit tests.

This way, you could keep your calls to CommonData.GetTotal() just like before without changing this part of the code (I heard some people call this something like Static Gateway Pattern or something similar).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top