调用依赖于数据访问层的方法的单元测试方法
我的代码库没有任何单元测试,我正在尝试向其中添加一些单元测试。该代码是 VB.NET,但不是非常面向对象。我们使用 NUnit 进行单元测试。许多类都有共享/静态方法。
我正在尝试对调用使用数据访问层的其他方法的方法进行单元测试。所以我的代码如下所示:
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
所以现在我面临着弄清楚如何测试这些方法的问题。我们有很多像 DoSomething 这样的方法,它们都在传递连接字符串时对数据访问层类进行静态调用。
在这种情况下我该怎么做才能避免对数据库进行真正的调用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该模拟数据库。也就是说,使用具有相同接口的对象,但不访问数据库。该对象可以是手写的,也可以由模拟框架生成。然后,单元测试查询模拟对象以断言已按预期调用。
然后,您的测试类将调用模拟数据库类的实例,而不是真正的数据库对象;这种技术称为 依赖注入 :您可以将模拟对象传递给被测试的类,或者依靠工厂返回正确的类实例,具体取决于正在单元测试或在生产中执行的代码。
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.