擅长:python、mysql、java
<p>您刚刚重新发现了测试之所以重要的一个最有说服力的原因:它告诉您什么时候设计不好。</p>
<p>换言之,可测试性是<em>质量</em>的良好一级代理。请考虑以下几点:</p>
<pre><code>class DB(object):
def __init__(self, **credentials):
self._connect = partial(pymysql.connect, **credentials)
def query(self, q_str, params):
with self._connect as conn:
with conn.cursor() as cur:
cur.execute(q_str, params)
return cur.fetchall()
# now for usage
test_credentials = {
# use credentials to a fake database
}
test_db = DB(**test_credentials)
test_db.query(write_query, list_of_fake_params)
results = test_db.query(read_query)
assert results = what_the_results_should_be
</code></pre>
<p>如果使用多个数据库,可以使用多态性,或者根据API的相似性,将特定的DB作为对象的构造函数参数。</p>