Question

I want each testCase while loading setup function should declare different values of "x". Is there a way I can achieve in setUp function. Sample code is mentioned below. How to change PSEUDO CODE in setUp function below?

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.

Was it helpful?

Solution

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). 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.

OTHER TIPS

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top