简体   繁体   English

如何测试数据检索模块?

[英]How to test a data retrieval module?

I am working on a project and have a data retrieval module written on python. 我正在一个项目上,并且有一个用python编写的数据检索模块。 All it does is build a query using string manipulations and then executes the query using another module (a connection module). 它所做的只是使用字符串操作构建查询,然后使用另一个模块(连接模块)执行查询。 I want to make unit tests properly. 我想正确进行单元测试。 Does anyone have any recommendations on techniques? 有人对技术有什么建议吗? Is mocking a proper way to do so? 嘲笑是正确的方法吗?

Your code consists of a computational part (building a query string) and an interactional part, where the actual communication with the data base is performed. 您的代码由计算部分(构建查询字符串)和交互部分组成,在其中进行与数据库的实际通信。 If these two are combined, the code looks as follows: 如果将两者结合起来,代码如下:

def fetchData(self):
    query = ... some string building logic here
    results = ... database access using query

In code like this, just to check the string building logic in unit-testing, you would mock the data base access (to avoid the dependency on the data base in your unit-tests for various reasons). 在这样的代码中,仅为了检查单元测试中的字符串构建逻辑,就可以模拟数据库访问(以避免由于各种原因而导致对单元测试中数据库的依赖)。 In the subsequent integration testing, you would then test the interaction of fetchData with the real data base. 在随后的集成测试中,您将测试fetchData与真实数据库的交互。

An alternative approach is to extract the algorithmic part (the creation of the query string) into a separate method such that you can easily test this part independently. 另一种方法是将算法部分(查询字符串的创建)提取到单独的方法中,以便您可以轻松地独立测试该部分。

def buildQuery(self):
    query = ... some string building logic here
    return query

def fetchData(self):
    query = self.buildQuery()
    results = ... database access using query

This makes your unit-testing simpler, because for the testing of buildQuery you don't need to do any mocking of the data base. 这使您的单元测试更加简单,因为对于buildQuery的测试,您无需对数据库进行任何buildQuery Again, in integration testing you would then test the interaction of fetchData with the real data base. 同样,在集成测试中,您将然后测试fetchData与真实数据库的交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM