views:

80

answers:

1

I work on codebase that doesn't have any unit tests in place and I'm trying to get add some unit testing to it. The code is VB.NET but isn't very object oriented. We're using NUnit for unit testing. A lot of the classes have shared/static methods.

I'm trying to unit test a method that calls other methods that use the data access layer. So my code looks something like the following:

Public Class FooBar
    Private CONN_STRING As String = "<Connection String Goes Here>"

    Public Shared Function DoSomething(obj As Object) As Object
        'This is the method I want to unit test.
        '...

        Dim myLog As New Log
        myLog.Message = "Foobar"
        LogTable.InsertLog(CONN_STRING, myLog)

        Return someObject
    End Function
End Class


Public Class LogTable
    Public Shared Function InsertLog(connectionString As String, log As Log) As Integer
       Dim db As New DBTable(connectionString, "tblLog")
       Return db.Insert(log)
    End Function
End Class

So now I'm faced with the problem of figuring out how to test these methods. We have A LOT of methods like DoSomething and they all make static calls to data access layer classes while passing around a Connection String.

What can I do in this situation to avoid making a real call to the DB?

+1  A: 

You should mock the DB. That is, use an object that has the same interface, but does not access the DB. This object can either be hand written, or generated by a mock framework. The unit tests then queries the mock object to assert in was invoked as expected.

Then you have your class under test invoke an instance of the mock DB class, instead of the real DB object ; this technique is called dependency injection : you can either pass the mock object to the class under test, or rely on a Factory to return the correct class instance, depending on the code being unit tested or executed in production.

philippe