1

I was wondering if you can help me understand a moq concept... I have a method I want to test. It contains a data access method that I want to mock.

The method to test:

Public Function GetReport(ByVal district As String, ByVal hub As String, ByVal dateFrom As Date, ByVal dateTo As Date, ByVal response As HttpResponse) As String
        Dim msg As String = String.Empty
        Dim rs As New ReportingService

        _dt = _dal.GetData(district, hub, dateFrom, dateTo)

        If _dt.Rows.Count <= 0 Then
            msg = "There were no records found for the selected criteria."
        ElseIf _dt.Rows.Count + 1 > 65536 Then
            msg = "Too many rows - Export to Excel not possible."
        Else
            rs.Export(_dt, "AcceptanceOfOffer", response)
        End If

        Return msg
    End Function 

I want to test the control logic. If the datatable has 0,1 or many rows a different message should be returned.. I don't care about the result of _dal.GetData, it's the method I am hoping to mock.

Here's my test, no nunit or anything like that:

'''<summary>
'''A test for GetReport
'''</summary>
<TestMethod()> _
Public Sub GetReportTest()
    'Create a fake object
    Dim mock = New Mock(Of IAcceptanceOfferDAL)
    'Create the real data to be returned by the fake
    Dim returnDt As DataTable = New DataTable()
    returnDt.Columns.Add("District", Type.GetType("System.String"))
    returnDt.Columns.Add("Hub", Type.GetType("System.String"))
    returnDt.Columns.Add("dateFrom", Type.GetType("System.DateTime"))
    returnDt.Columns.Add("dateTo", Type.GetType("System.DateTime"))
    returnDt.Rows.Add("District", "Hub", Date.Today, Date.Today)

    'Setup the fake so that when the method is called the data created above will be returned
    mock.Setup(Function(f) f.GetData(It.IsAny(Of String), It.IsAny(Of String), It.IsAny(Of Date), It.IsAny(Of Date))).Returns(returnDt)

    'Call the real method with the expectation that when it calls GetData it will use our mock object
    Dim target = New AcceptanceOfferBLL

    Dim response As HttpResponse
    Dim actual = target.GetReport("district", "hub", Date.Today, Date.Today, response)
    'Because our mock returns 1 row it will skip over our if statements and should return string.empty
    Assert.AreEqual("", actual)

End Sub

Just in case it's relevant, the DAL class and method I am trying to mock.

Public Interface IAcceptanceOfferDAL
    Function GetData(ByVal district As String, ByVal site As String, ByVal dateFrom As Date, ByVal dateTo As Date) As DataTable
End Interface

Public Class AcceptanceOfferDAL : Implements IAcceptanceOfferDAL
    Private _ds As New DataService.DataAccess
    Private _sNameSP As String = ""
    Private _listSQLParams As New List(Of SqlParameter)

    Public Function GetData(ByVal district As String, ByVal site As String, ByVal dateFrom As Date, ByVal dateTo As Date) As DataTable Implements IAcceptanceOfferDAL.GetData
        _sNameSP = "up_AcceptanceHub_get"

        Dim sqlParam As SqlParameter = New SqlParameter("@district", district)
        Dim sqlParam1 As SqlParameter = New SqlParameter("@hub", site)
        Dim sqlParam2 As SqlParameter = New SqlParameter("@DateFrom", dateFrom)
        Dim sqlParam3 As SqlParameter = New SqlParameter("@DateTo", dateTo)

        _listSQLParams.Add(sqlParam)
        _listSQLParams.Add(sqlParam1)
        _listSQLParams.Add(sqlParam2)
        _listSQLParams.Add(sqlParam3)

        Return (_ds.LoadDataTableByID(_listSQLParams, _sNameSP))

    End Function

End Class

Obviously this doesn't work, I've checked the moq quickstart and other places without success. Is this even possible or should I be using .verify or something else? This post has the structure I want to use except in that case the mocked object is passed as an argument to the method.

Community
  • 1
  • 1
Andrew
  • 38
  • 6
  • Could you clarify what "this doesn't work" means? – PatrickSteele Oct 25 '11 at 23:38
  • The code goes to the real concrete dal.GetData method, rather than a proxy version of the method. It tries to connect to a database and return info rather than the dummy dataset I created in the test. – Andrew Oct 26 '11 at 08:25
  • You never pass the mock IAcceptanceOfferDAL to AcceptanceOfferBLL. How is the "_dal" variable of AcceptanceOfferBLL created? It should be a constructor dependency that gets injected via an IOC container at runtime, but is mocked during testing. – PatrickSteele Oct 26 '11 at 13:45
  • Is dependency injection the only option? Could you explain it's benefit outside of getting the test to work? – Andrew Oct 26 '11 at 23:49
  • Using an IoC container with dependency injection gives lots of benefits -- especially for testability. Some google searches for "inversion of control pattern" will yield lots of results. – PatrickSteele Oct 27 '11 at 11:52

1 Answers1

0

The GetReport method is dependent on _dal, which is defined outside of the GetReport method.

Thus, despite creating a mock object for IAcceptanceOfferDAL, that mock object doesn't come into play because GetReport only knows to use the _dal object that was instantiated elsewhere.

To get around this dependency, the _dal object needs to be passed into the method as a parameter.

Public Function GetReport(ByVal district As String
                        , ByVal hub As String
                        , ByVal dateFrom As Date
                        , ByVal dateTo As Date
                        , ByVal response As HttpResponse
                        , ByVal _dal As IAcceptanceOfferDAL) As String

By doing this, the mock of IAcceptanceOfferDAL and the setup for its GetData function will be in play when testing the GetReport method like so:

Dim actual =  target.GetReport("district"
                             , "hub"
                             , Date.Today
                             , Date.Today
                             , response
                             , mock)

So, to be clear, changing the GetReport method such that it accepts an instance of IAcceptanceOfferDAL as a parameter allows a mock object to be passed into this method when testing, and the ability to pass in that mock, of course, provides the desired control over the return value of the GetData method.

Hope this helps

jimmym715
  • 1,512
  • 1
  • 16
  • 25
  • Great. That will certainly work for testing, but having to change the code in this fashion just so that I can test it seems a little ... I dunno, wrong? – Andrew Oct 26 '11 at 22:15
  • I see this as a change in mindset: any object or service that would introduce a dependency to a method should be referenced by an interface, and that interface should be passed as a parameter to the method. This allows a unit test to pass a mock of the object or service, while calls to the method within the application will pass an instance of an object or service that implements the same interface, complete with the dependencies that the unit test needed to avoid. – jimmym715 Oct 30 '11 at 02:01