开发者

Unit testing methods that call methods with dependencies to the data access layer

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 ver开发者_开发百科y 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜