<h2>Python框架中的<code>setUp()</code>和<code>setUpClass()</code>有什么区别?</h2>
<p>主要的区别(正如本杰明·霍奇森在回答中指出的那样)是<code>setUpClass</code>只调用一次,即在所有测试之前,而<code>setUp</code>则在每次测试之前立即调用。(注意:这同样适用于其他xUnit测试框架中的等效方法,而不仅仅是Python的<code>unittest</code>)</p>
<p>从<code>unittest</code><a href="https://docs.python.org/3/library/unittest.html" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p><code>setUpClass()</code></p>
<p>A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():</p>
</blockquote>
<pre><code>@classmethod
def setUpClass(cls):
...
</code></pre>
<p>以及:</p>
<blockquote>
<p><code>setUp()</code></p>
<p>Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.</p>
</blockquote>
<h2>为什么要用一种方法来处理安装程序?</h2>
<p>这部分问题尚未得到回答。根据我对Gearon回答的评论,<code>setUp</code>方法用于所有测试通用的fixture元素(以避免在每个测试中重复该代码)。我发现这通常是有用的,因为消除重复(通常)可以提高可读性并减少维护负担。</p>
<p><code>setUpClass</code>方法适用于昂贵的元素,您宁愿只做一次,例如打开数据库连接、打开文件系统上的临时文件、加载共享库进行测试等。在每次测试之前执行这些操作会使测试套件过慢,因此我们只在所有测试之前执行一次。这是测试独立性的一个轻微退化,但在某些情况下是一个必要的优化。可以说,不应该在单元测试中做这样的事情,因为通常可以模拟数据库/文件系统/库/任何东西,而不使用真正的东西。因此,我发现很少需要<code>setUpClass</code>。然而,当需要测试上述示例(或类似示例)时,它是有用的。</p>