Reputation: 771
When creating a unit test, I cannot seem to set attributes in one test, to be used in another test. The two tests in question must happen in sequential order because the attribute set in one test is directly used in another test.
To give an example, let's say I have a class called Foo, which has two methods, one called test_set_bar which sets an attribute bar, and another called test_get_bar which gets it:
Whenever I try to run the two 'tests' however, I get the following error:
AttributeError: 'Test_Foo' object has no attribute 'bar'
Thus, I cannot seem to set attributes in the normal way.
I know that I can do this in the setUp, however, the thing that would need to go in setUp itself is actually the return value of a function, which itself is being tested. Thus, it must be set during the execution of a test.
Upvotes: 2
Views: 4383
Reputation: 2015
You can make use of setup method for that purpose.
from unittest import TestCase
class TestFoo(TestCase):
def setUp(self):
self.bar = 1
def test_bar(self):
assert self.bar, 1
Upvotes: 2