简体   繁体   English

Python:在unittest.TestCase中基于TestCase修改SetUp

[英]Python: Modify SetUp based on TestCase in unittest.TestCase

I want each testCase while loading setup function should declare different values of "x". 我希望每个testCase在加载设置函数时都应声明不同的“x”值。 Is there a way I can achieve in setUp function. 有没有办法在setUp函数中实现。 Sample code is mentioned below. 示例代码如下所述。 How to change PSEUDO CODE in setUp function below? 如何更改下面的setUp函数中的PSEUDO CODE

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):

        # ***PSEUDO CODE***
        x = 10 # if test_shuffle uses setUp()
        x = 20 # if test_choice uses setUp()
        x = 30 # if test_sample uses setUp()
        # ***PSEUDO CODE***

    def test_shuffle(self):
        #test_shuffle

    def test_choice(self):
        #test_choice

    def test_sample(self):
        #test_choice

if __name__ == '__main__':
    unittest.main()

I can achieve by writing each testcase in different file but I would drastically increases number of files. 我可以通过在不同的文件中编写每个测试用例来实现,但是我会大幅增加文件数量。

Perhaps I am missing the point, but the assignment in your pseudo code could just be moved to the start of the corresponding test. 也许我错过了这一点,但伪代码中的赋值可能只是移动到相应测试的开头。 If the "assignment" is more complex, or spans multiple tests, then just create functions outside the test case but inside the file and the corresponding tests invoke whatever functions are supposed to be part of their "setUp". 如果“赋值”更复杂,或跨越多个测试,那么只需在测试用例之外但在文件内部创建函数,相应的测试会调用任何函数应该是它们的“setUp”的一部分。

One unittest file thematically captures tests that all cover similar features. 一个单元测试文件主题捕获所有涵盖类似功能的测试。 The setup is used to get that feature into a testable state. 该设置用于将该功能置于可测试状态。

Move that assignment of X into the actual test method (keeps X = 0 in the setup if you want every test to actually have an X). 将X的分配移动到实际的测试方法中(如果您希望每个测试实际上都有X,则在设置中保持X = 0)。 It makes it clearer when reading the test exactly what is happening and how it is being tested. 在阅读测试时,它会更清楚地显示正在发生的事情以及测试方式。 You shouldn't have conditional logic that affect how tests work inside your setup function because you are introducing complexity into the test's preconditions, which means you have a much larger surface area for errors. 您不应该有影响测试在设置函数中工作方式的条件逻辑,因为您在测试的前提条件中引入了复杂性,这意味着您有更大的表面区域来表示错误。

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

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