user2290820
user2290820

Reputation: 2749

Reuse a unittest method in another method under same test class

Lets say there is a testcase like this testing two features using unittest

class Test(unittest.TestCase):
    def setUp(self):
        self.something = X()
    def test_this(self):
        assert self.something.part1()
    def test_next(self):
        assert self.something.part2()

In the setUp the object will store self.something.

What if procedure test_next depends upon self.something.part1()?

How can self.something.part1() be reused in test_next?

I don't want to create stubs. I want to look for feature in unittest if it makes this possible and not go for mock.

Upvotes: 0

Views: 898

Answers (1)

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44112

You shall not make your test cases inter-dependent. Either move the dependent stuff to setUp, or put it into non testing share method prepare_something_part1 and call this from all related test cases, but do not mess up your test suite with interdependency which is difficult to maintain and use.

Conclusion from our chat

Code reuse is good thing, test driven development too.

With test driven development it is essential to write test cases and code reuse (in test cases) is not so important.

Simply: relax, play with writing test case and code reuse in test cases will naturally come in soon.

Upvotes: 1

Related Questions